2015年4月28日 星期二
ViewPager with Fragment
public class CollectionOfItems extends FragmentActivity {
private List<Fragment> fragments;
.
.
略
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.collectionofitems);
InitImageView();//初始化標頭並對它設定click偵聽和編號0.1.2
textView1 = (TextView) findViewById(R.id.text1);
.
.
略
textView1.setOnClickListener(new MyOnClickListener(0));
.
.
略
fragments = new ArrayList<Fragment>();
viewPager = (ViewPager) findViewById(R.id.viewPager); //取得viewPager資源
Fragment f1 = new Fragment1();
Fragment f2 = new Fragment2();
.
.
fragments.add(f1);
fragments.add(f2);
.
.
fragmentAdapter fa = new fragmentAdapter(getSupportFragmentManager(),fragments);
viewPager.setAdapter(fa);
viewPager.setCurrentItem(0);//頁卡預設為第一頁
viewPager.setOnPageChangeListener(new MyOnPageChangeListener());
}
//實現FragmentPagerAdapter
public class fragmentAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
private FragmentManager fm;
public fragmentAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
public fragmentAdapter(FragmentManager fm) {
super(fm);
this.fm = fm;
}
@Override
public Fragment getItem(int arg0) {
return fragments.get(arg0);
}
@Override
public int getCount() {
return fragments.size();
}
}
-------------------------------------------------------------------------------------------------
Fragment1.java
public class Fragment1 extends Fragment{
private View rootView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment1, container, false);
return rootView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
.
.
要執行的程式
.
.
.
}
-----------------------------------------------------------------------------------------------
fragment1.xml
隨意..
2015年4月27日 星期一
AlertDialog詳解
出處:http://www.imyukin.com/?p=236
AlertDialog的構造方法全部是Protected的,所以不能直接通過new一個AlertDialog來創建出一個AlertDialog。
要創建一個AlertDialog,就要用到AlertDialog.Builder中的create()方法。
使用AlertDialog.Builder創建對話框需要了解以下幾個方法:
setTitle :為對話框設置標題
setIcon :為對話框設置圖標
setMessage:為對話框設置內容
setView :給對話框設置自定義樣式
setItems :設置對話框要顯示的一個list,一般用於顯示幾個命令時
setMultiChoiceItems :用來設置對話框顯示一系列的複選框
setNeutralButton :普通按鈕
setPositiveButton :給對話框添加”Yes”按鈕
setNegativeButton :對話框添加”No”按鈕
create :創建對話框
show :顯示對話框
一、簡單的AlertDialog
下面,創建一個簡單的ALertDialog並顯示它:
package com . tianjf ;
import android . app . Activity ;
import android . app . AlertDialog ;
import android . app . Dialog ;
import android . os . Bundle ;
public class Dialog_AlertDialogDemoActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate ( Bundle savedInstanceState ) {
super . onCreate ( savedInstanceState );
setContentView ( R . layout . main );
Dialog alertDialog = new AlertDialog . Builder ( this ).
setTitle ( "對話框的標題" ).
setMessage ( "對話框的內容" ).
setIcon ( R . drawable . ic_launcher ).
create ();
alertDialog . show ();
}
}
運行結果如下:
二、帶按鈕的AlertDialog
上面的例子很簡單,下面我們在這個AlertDialog上面加幾個Button,實現刪除操作的提示對話框
package com . tianjf ;
import android . app . Activity ;
import android . app . AlertDialog ;
import android . app . Dialog ;
import android . content . DialogInterface ;
import android . os . Bundle ;
public class Dialog_AlertDialogDemoActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate ( Bundle savedInstanceState ) {
super . onCreate ( savedInstanceState );
setContentView ( R . layout . main );
Dialog alertDialog = new AlertDialog . Builder ( this ).
setTitle ( "確定刪除?" ).
setMessage ( "您確定刪除該條信息嗎?" ).
setIcon ( R . drawable . ic_launcher ).
setPositiveButton ( "確定" , new DialogInterface . OnClickListener () {
@Override
public void onClick ( DialogInterface dialog , int which ) {
// TODO Auto-generated method stub
}
}).
setNegativeButton ( "取消" , new DialogInterface . OnClickListener () {
@Override
public void onClick ( DialogInterface dialog , int which ) {
// TODO Auto-generated method stub
}
}).
setNeutralButton ( "查看詳情" , new DialogInterface . OnClickListener () {
@Override
public void onClick ( DialogInterface dialog , int which ) {
// TODO Auto-generated method stub
}
}).
create ();
alertDialog . show ();
}
}
在這個例子中,我們定義了三個按鈕,分別是”Yes”按鈕,”No”按鈕以及一個普通按鈕,每個按鈕都有onClick事件,TODO的地方可以放點了按鈕之後想要做的一些處理
看一下運行結果:
可以看到三個按鈕添加到了AlertDialog上,三個沒有添加事件處理的按鈕,點了只是關閉對話框,沒有任何其他操作。
三、類似ListView的AlertDialog
用setItems(CharSequence[] items, final OnClickListener listener)方法來實現類似ListView的AlertDialog
第一個參數是要顯示的數據的數組,第二個參數是點擊某個item的觸發事件
package com . tianjf ;
import android . app . Activity ;
import android . app . AlertDialog ;
import android . app . Dialog ;
import android . content . DialogInterface ;
import android . os . Bundle ;
import android . widget . Toast ;
public class Dialog_AlertDialogDemoActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate ( Bundle savedInstanceState ) {
super . onCreate ( savedInstanceState );
setContentView ( R . layout . main );
final String [] arrayFruit = new String [] { "蘋果" , "橘子" , "草莓" , "香蕉" };
Dialog alertDialog = new AlertDialog . Builder ( this ).
setTitle ( "你喜 歡吃哪種水果?" ).
setIcon ( R . drawable . ic_launcher )
. setItems ( arrayFruit , new DialogInterface . OnClickListener () {
@Override
public void onClick ( DialogInterface dialog , int which ) {
Toast . makeText ( Dialog_AlertDialogDemoActivity . this , arrayFruit [ which ], Toast . LENGTH_SHORT ). show ();
}
}).
setNegativeButton ( "取消" , new DialogInterface . OnClickListener () {
@Override
public void onClick ( DialogInterface dialog , int which ) {
// TODO Auto-generated method stub
}
}).
create ();
alertDialog . show ();
}
}
運行結果如下:
四、類似RadioButton的AlertDialog
用setSingleChoiceItems(CharSequence[] items, int checkedItem, final OnClickListener listener)方法來實現類似RadioButton的AlertDialog
第一個參數是要顯示的數據的數組,第二個參數是初始值(初始被選中的item),第三個參數是點擊某個item的觸發事件
在這個例子裡 面我們設了一個selectedFruitIndex用來記住選中的item的index
package com . tianjf ;
import android . app . Activity ;
import android . app . AlertDialog ;
import android . app . Dialog ;
import android . content . DialogInterface ;
import android . os . Bundle ;
import android . widget . Toast ;
public class Dialog_AlertDialogDemoActivity extends Activity {
private int selectedFruitIndex = 0 ;
/** Called when the activity is first created. */
@Override
public void onCreate ( Bundle savedInstanceState ) {
super . onCreate ( savedInstanceState );
setContentView ( R . layout . main );
final String [] arrayFruit = new String [] { "蘋果" , "橘子" , "草莓" , "香蕉" };
Dialog alertDialog = new AlertDialog . Builder ( this ).
setTitle ( "你喜 歡吃哪種水果?" ).
setIcon ( R . drawable . ic_launcher )
. setSingleChoiceItems ( arrayFruit , 0 , new DialogInterface . OnClickListener () {
@Override
public void onClick ( DialogInterface dialog , int which ) {
selectedFruitIndex = which ;
}
}).
setPositiveButton ( "確認" , new DialogInterface . OnClickListener () {
@Override
public void onClick ( DialogInterface dialog , int which ) {
Toast . makeText ( Dialog_AlertDialogDemoActivity . this , arrayFruit [ selectedFruitIndex ], Toast . LENGTH_SHORT ). show ();
}
}).
setNegativeButton ( "取消" , new DialogInterface . OnClickListener () {
@Override
public void onClick ( DialogInterface dialog , int which ) {
// TODO Auto-generated method stub
}
}).
create ();
alertDialog . show ();
}
}
運行結果如下:
五、類似CheckBox的AlertDialog
用setMultiChoiceItems(CharSequence[] items, boolean[] checkedItems, final OnMultiChoiceClickListener listener)方法來實現類似CheckBox的AlertDialog
第一個參數是要顯示的數據的數組,第二個參數是選中狀態的數組,第三個參數是點擊某個item的觸發事件
package com . tianjf ;
import android . app . Activity ;
import android . app . AlertDialog ;
import android . app . Dialog ;
import android . content . DialogInterface ;
import android . os . Bundle ;
import android . widget . Toast ;
public class Dialog_AlertDialogDemoActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate ( Bundle savedInstanceState ) {
super . onCreate ( savedInstanceState );
setContentView ( R . layout . main );
final String [] arrayFruit = new String [] { "蘋果" , "橘子" , "草莓" , "香蕉" };
final boolean [] arrayFruitSelected = new boolean [] { true , true , false , false };
Dialog alertDialog = new AlertDialog . Builder ( this ).
setTitle ( "你喜 歡吃哪種水果?" ).
setIcon ( R . drawable . ic_launcher )
. setMultiChoiceItems ( arrayFruit , arrayFruitSelected , new DialogInterface . OnMultiChoiceClickListener () {
@Override
public void onClick ( DialogInterface dialog , int which , boolean isChecked ) {
arrayFruitSelected [ which ] = isChecked ;
}
}).
setPositiveButton ( "確認" , new DialogInterface . OnClickListener () {
@Override
public void onClick ( DialogInterface dialog , int which ) {
StringBuilder stringBuilder = new StringBuilder ();
for ( int i = 0 ; i < arrayFruitSelected . length ; i ++) {
if ( arrayFruitSelected [ i ] == true )
{
stringBuilder . append ( arrayFruit [ i ] + "、" );
}
}
Toast . makeText ( Dialog_AlertDialogDemoActivity . this , stringBuilder . toString (), Toast . LENGTH_SHORT ). show ();
}
}).
setNegativeButton ( "取消" , new DialogInterface . OnClickListener () {
@Override
public void onClick ( DialogInterface dialog , int which ) {
// TODO Auto-generated method stub
}
}).
create ();
alertDialog . show ();
}
}
運行結果如下:
六、自定義View的AlertDialog
有時候我們不能滿足系統自帶的AlertDialog風格,就比如說我們要實現一個Login畫面,有用戶名和密碼,這時我們就要用到自定義View的AlertDialog
先創建Login畫面的佈局文件
<? xml version = "1.0" encoding = "utf-8" ?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent"
android:orientation = "vertical" >
<LinearLayout
android:layout_width = "fill_parent"
android:layout_height = "wrap_content"
android:gravity = "center" >
<TextView
android:layout_width = "0dip"
android:layout_height = "wrap_content"
android:layout_weight = "1"
android:text = "@string/user" />
<EditText
android:layout_width = "0dip"
android:layout_height = "wrap_content"
android:layout_weight = "1" />
</LinearLayout>
<LinearLayout
android:layout_width = "fill_parent"
android:layout_height = "wrap_content"
android:gravity = "center" >
<TextView
android:layout_width = "0dip"
android:layout_height = "wrap_content"
android:layout_weight = "1"
android:text = "@string/passward" />
<EditText
android:layout_width = "0dip"
android:layout_height = "wrap_content"
android:layout_weight = "1" />
</LinearLayout>
</LinearLayout>
然後在Activity裡面把Login畫面的佈局文件添加到AlertDialog上
package com . tianjf ;
import android . app . Activity ;
import android . app . AlertDialog ;
import android . app . Dialog ;
import android . content . DialogInterface ;
import android . os . Bundle ;
import android . view . LayoutInflater ;
import android . view . View ;
public class Dialog_AlertDialogDemoActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate ( Bundle savedInstanceState ) {
super . onCreate ( savedInstanceState );
setContentView ( R . layout . main );
// 取得自定義View
LayoutInflater layoutInflater = LayoutInflater . from ( this );
View myLoginView = layoutInflater . inflate ( R . layout . login , null );
Dialog alertDialog = new AlertDialog . Builder ( this ).
setTitle ( "用戶登錄" ).
setIcon ( R . drawable . ic_launcher ).
setView ( myLoginView ).
setPositiveButton ( "登錄" , new DialogInterface . OnClickListener () {
@Override
public void onClick ( DialogInterface dialog , int which ) {
// TODO Auto-generated method stub
}
}).
setNegativeButton ( "取消" , new DialogInterface . OnClickListener () {
@Override
public void onClick ( DialogInterface dialog , int which ) {
// TODO Auto-generated method stub
}
}).
create ();
alertDialog . show ();
}
}
運行結果如下:
AlertDialog的構造方法全部是Protected的,所以不能直接通過new一個AlertDialog來創建出一個AlertDialog。
要創建一個AlertDialog,就要用到AlertDialog.Builder中的create()方法。
使用AlertDialog.Builder創建對話框需要了解以下幾個方法:
setTitle :為對話框設置標題
setIcon :為對話框設置圖標
setMessage:為對話框設置內容
setView :給對話框設置自定義樣式
setItems :設置對話框要顯示的一個list,一般用於顯示幾個命令時
setMultiChoiceItems :用來設置對話框顯示一系列的複選框
setNeutralButton :普通按鈕
setPositiveButton :給對話框添加”Yes”按鈕
setNegativeButton :對話框添加”No”按鈕
create :創建對話框
show :顯示對話框
一、簡單的AlertDialog
下面,創建一個簡單的ALertDialog並顯示它:
package com . tianjf ;
import android . app . Activity ;
import android . app . AlertDialog ;
import android . app . Dialog ;
import android . os . Bundle ;
public class Dialog_AlertDialogDemoActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate ( Bundle savedInstanceState ) {
super . onCreate ( savedInstanceState );
setContentView ( R . layout . main );
Dialog alertDialog = new AlertDialog . Builder ( this ).
setTitle ( "對話框的標題" ).
setMessage ( "對話框的內容" ).
setIcon ( R . drawable . ic_launcher ).
create ();
alertDialog . show ();
}
}
運行結果如下:
二、帶按鈕的AlertDialog
上面的例子很簡單,下面我們在這個AlertDialog上面加幾個Button,實現刪除操作的提示對話框
package com . tianjf ;
import android . app . Activity ;
import android . app . AlertDialog ;
import android . app . Dialog ;
import android . content . DialogInterface ;
import android . os . Bundle ;
public class Dialog_AlertDialogDemoActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate ( Bundle savedInstanceState ) {
super . onCreate ( savedInstanceState );
setContentView ( R . layout . main );
Dialog alertDialog = new AlertDialog . Builder ( this ).
setTitle ( "確定刪除?" ).
setMessage ( "您確定刪除該條信息嗎?" ).
setIcon ( R . drawable . ic_launcher ).
setPositiveButton ( "確定" , new DialogInterface . OnClickListener () {
@Override
public void onClick ( DialogInterface dialog , int which ) {
// TODO Auto-generated method stub
}
}).
setNegativeButton ( "取消" , new DialogInterface . OnClickListener () {
@Override
public void onClick ( DialogInterface dialog , int which ) {
// TODO Auto-generated method stub
}
}).
setNeutralButton ( "查看詳情" , new DialogInterface . OnClickListener () {
@Override
public void onClick ( DialogInterface dialog , int which ) {
// TODO Auto-generated method stub
}
}).
create ();
alertDialog . show ();
}
}
在這個例子中,我們定義了三個按鈕,分別是”Yes”按鈕,”No”按鈕以及一個普通按鈕,每個按鈕都有onClick事件,TODO的地方可以放點了按鈕之後想要做的一些處理
看一下運行結果:
可以看到三個按鈕添加到了AlertDialog上,三個沒有添加事件處理的按鈕,點了只是關閉對話框,沒有任何其他操作。
三、類似ListView的AlertDialog
用setItems(CharSequence[] items, final OnClickListener listener)方法來實現類似ListView的AlertDialog
第一個參數是要顯示的數據的數組,第二個參數是點擊某個item的觸發事件
package com . tianjf ;
import android . app . Activity ;
import android . app . AlertDialog ;
import android . app . Dialog ;
import android . content . DialogInterface ;
import android . os . Bundle ;
import android . widget . Toast ;
public class Dialog_AlertDialogDemoActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate ( Bundle savedInstanceState ) {
super . onCreate ( savedInstanceState );
setContentView ( R . layout . main );
final String [] arrayFruit = new String [] { "蘋果" , "橘子" , "草莓" , "香蕉" };
Dialog alertDialog = new AlertDialog . Builder ( this ).
setTitle ( "你喜 歡吃哪種水果?" ).
setIcon ( R . drawable . ic_launcher )
. setItems ( arrayFruit , new DialogInterface . OnClickListener () {
@Override
public void onClick ( DialogInterface dialog , int which ) {
Toast . makeText ( Dialog_AlertDialogDemoActivity . this , arrayFruit [ which ], Toast . LENGTH_SHORT ). show ();
}
}).
setNegativeButton ( "取消" , new DialogInterface . OnClickListener () {
@Override
public void onClick ( DialogInterface dialog , int which ) {
// TODO Auto-generated method stub
}
}).
create ();
alertDialog . show ();
}
}
運行結果如下:
四、類似RadioButton的AlertDialog
用setSingleChoiceItems(CharSequence[] items, int checkedItem, final OnClickListener listener)方法來實現類似RadioButton的AlertDialog
第一個參數是要顯示的數據的數組,第二個參數是初始值(初始被選中的item),第三個參數是點擊某個item的觸發事件
在這個例子裡 面我們設了一個selectedFruitIndex用來記住選中的item的index
package com . tianjf ;
import android . app . Activity ;
import android . app . AlertDialog ;
import android . app . Dialog ;
import android . content . DialogInterface ;
import android . os . Bundle ;
import android . widget . Toast ;
public class Dialog_AlertDialogDemoActivity extends Activity {
private int selectedFruitIndex = 0 ;
/** Called when the activity is first created. */
@Override
public void onCreate ( Bundle savedInstanceState ) {
super . onCreate ( savedInstanceState );
setContentView ( R . layout . main );
final String [] arrayFruit = new String [] { "蘋果" , "橘子" , "草莓" , "香蕉" };
Dialog alertDialog = new AlertDialog . Builder ( this ).
setTitle ( "你喜 歡吃哪種水果?" ).
setIcon ( R . drawable . ic_launcher )
. setSingleChoiceItems ( arrayFruit , 0 , new DialogInterface . OnClickListener () {
@Override
public void onClick ( DialogInterface dialog , int which ) {
selectedFruitIndex = which ;
}
}).
setPositiveButton ( "確認" , new DialogInterface . OnClickListener () {
@Override
public void onClick ( DialogInterface dialog , int which ) {
Toast . makeText ( Dialog_AlertDialogDemoActivity . this , arrayFruit [ selectedFruitIndex ], Toast . LENGTH_SHORT ). show ();
}
}).
setNegativeButton ( "取消" , new DialogInterface . OnClickListener () {
@Override
public void onClick ( DialogInterface dialog , int which ) {
// TODO Auto-generated method stub
}
}).
create ();
alertDialog . show ();
}
}
運行結果如下:
五、類似CheckBox的AlertDialog
用setMultiChoiceItems(CharSequence[] items, boolean[] checkedItems, final OnMultiChoiceClickListener listener)方法來實現類似CheckBox的AlertDialog
第一個參數是要顯示的數據的數組,第二個參數是選中狀態的數組,第三個參數是點擊某個item的觸發事件
package com . tianjf ;
import android . app . Activity ;
import android . app . AlertDialog ;
import android . app . Dialog ;
import android . content . DialogInterface ;
import android . os . Bundle ;
import android . widget . Toast ;
public class Dialog_AlertDialogDemoActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate ( Bundle savedInstanceState ) {
super . onCreate ( savedInstanceState );
setContentView ( R . layout . main );
final String [] arrayFruit = new String [] { "蘋果" , "橘子" , "草莓" , "香蕉" };
final boolean [] arrayFruitSelected = new boolean [] { true , true , false , false };
Dialog alertDialog = new AlertDialog . Builder ( this ).
setTitle ( "你喜 歡吃哪種水果?" ).
setIcon ( R . drawable . ic_launcher )
. setMultiChoiceItems ( arrayFruit , arrayFruitSelected , new DialogInterface . OnMultiChoiceClickListener () {
@Override
public void onClick ( DialogInterface dialog , int which , boolean isChecked ) {
arrayFruitSelected [ which ] = isChecked ;
}
}).
setPositiveButton ( "確認" , new DialogInterface . OnClickListener () {
@Override
public void onClick ( DialogInterface dialog , int which ) {
StringBuilder stringBuilder = new StringBuilder ();
for ( int i = 0 ; i < arrayFruitSelected . length ; i ++) {
if ( arrayFruitSelected [ i ] == true )
{
stringBuilder . append ( arrayFruit [ i ] + "、" );
}
}
Toast . makeText ( Dialog_AlertDialogDemoActivity . this , stringBuilder . toString (), Toast . LENGTH_SHORT ). show ();
}
}).
setNegativeButton ( "取消" , new DialogInterface . OnClickListener () {
@Override
public void onClick ( DialogInterface dialog , int which ) {
// TODO Auto-generated method stub
}
}).
create ();
alertDialog . show ();
}
}
運行結果如下:
六、自定義View的AlertDialog
有時候我們不能滿足系統自帶的AlertDialog風格,就比如說我們要實現一個Login畫面,有用戶名和密碼,這時我們就要用到自定義View的AlertDialog
先創建Login畫面的佈局文件
<? xml version = "1.0" encoding = "utf-8" ?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent"
android:orientation = "vertical" >
<LinearLayout
android:layout_width = "fill_parent"
android:layout_height = "wrap_content"
android:gravity = "center" >
<TextView
android:layout_width = "0dip"
android:layout_height = "wrap_content"
android:layout_weight = "1"
android:text = "@string/user" />
<EditText
android:layout_width = "0dip"
android:layout_height = "wrap_content"
android:layout_weight = "1" />
</LinearLayout>
<LinearLayout
android:layout_width = "fill_parent"
android:layout_height = "wrap_content"
android:gravity = "center" >
<TextView
android:layout_width = "0dip"
android:layout_height = "wrap_content"
android:layout_weight = "1"
android:text = "@string/passward" />
<EditText
android:layout_width = "0dip"
android:layout_height = "wrap_content"
android:layout_weight = "1" />
</LinearLayout>
</LinearLayout>
然後在Activity裡面把Login畫面的佈局文件添加到AlertDialog上
package com . tianjf ;
import android . app . Activity ;
import android . app . AlertDialog ;
import android . app . Dialog ;
import android . content . DialogInterface ;
import android . os . Bundle ;
import android . view . LayoutInflater ;
import android . view . View ;
public class Dialog_AlertDialogDemoActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate ( Bundle savedInstanceState ) {
super . onCreate ( savedInstanceState );
setContentView ( R . layout . main );
// 取得自定義View
LayoutInflater layoutInflater = LayoutInflater . from ( this );
View myLoginView = layoutInflater . inflate ( R . layout . login , null );
Dialog alertDialog = new AlertDialog . Builder ( this ).
setTitle ( "用戶登錄" ).
setIcon ( R . drawable . ic_launcher ).
setView ( myLoginView ).
setPositiveButton ( "登錄" , new DialogInterface . OnClickListener () {
@Override
public void onClick ( DialogInterface dialog , int which ) {
// TODO Auto-generated method stub
}
}).
setNegativeButton ( "取消" , new DialogInterface . OnClickListener () {
@Override
public void onClick ( DialogInterface dialog , int which ) {
// TODO Auto-generated method stub
}
}).
create ();
alertDialog . show ();
}
}
運行結果如下:
2015年4月24日 星期五
Fragment解析
原文: http://blog.csdn.net/guolin_blog/article/details/8881711
http://cheng-min-i-taiwan.blogspot.tw/2013/01/fragment.html
http://cheng-min-i-taiwan.blogspot.tw/2012/04/android-fragment-hellofragment.html
而如果現在程序運行在橫屏模式的平板上,兩個Fragment就可以嵌入在同一個Activity中了,如下圖所示:
由此可以看出,使用Fragment可以讓我們更加充分地利用平板的屏幕空間,下面我們一起來探究下如何使用Fragment。
首先需要注意,Fragment是在3.0版本引入的,如果你使用的是3.0之前的系統,需要先導入android-support-v4的jar包才能使用Fragment功能。
新建一個項目叫做Fragments,然後在layout文件夾下新建一個名為fragment1.xml的佈局文件:
可以看到,這個佈局文件非常簡單,只有一個LinearLayout,裡面加入了一個TextView。我們如法炮製再新建一個fragment2.xml :
然後新建一個類Fragment1,這個類是繼承自Fragment的:
我們可以看到,這個類也非常簡單,主要就是加載了我們剛剛寫好的fragment1.xml佈局文件並返回。同樣的方法,我們再寫好Fragment2 :
然後打開或新建activity_main.xml作為主Activity的佈局文件,在裡面加入兩個Fragment的引用,使用android:name前綴來引用具體的Fragment:
最後打開或新建MainActivity作為程序的主Activity,裡面的代碼非常簡單,都是自動生成的:
現在我們來運行一次程序,就會看到,一個Activity很融洽地包含了兩個Fragment,這兩個Fragment平分了整個屏幕,效果圖如下:
動態添加Fragment
如果你是在使用模擬器運行,按下ctrl + F11切換到豎屏模式。效果如下圖所示:
Fragment的生命周期
和Activity一樣,Fragment也有自己的生命週期,理解Fragment的生命週期非常重要,我們通過代碼的方式來瞧一瞧Fragment的生命週期是什麼樣的:
可以看到,上面的代碼在每個生命週期的方法裡都打印了日誌,然後我們來運行一下程序,可以看到打印日誌如下:
這時點擊一下home鍵,打印日誌如下:
如果你再重新進入進入程序,打印日誌如下:
然後點擊back鍵退出程序,打印日誌如下:
看到這裡,我相信大多數朋友已經非常明白了,因為這和Activity的生命週期太相似了。只是有幾個Activity中沒有的新方法,這裡需要重點介紹一下:
onAttach方法:Fragment和Activity建立關聯的時候調用。
onCreateView方法:為Fragment加載佈局時調用。
onActivityCreated方法:當Activity中的onCreate方法執行完後調用。
onDestroyView方法:Fragment中的佈局被移除時調用。
onDetach方法:Fragment和Activity解除關聯的時候調用。
Fragment之間進行通信
通常情況下,Activity都會包含多個Fragment,這時多個Fragment之間如何進行通信就是個非常重要的問題了。我們通過一個例子來看一下,如何在一個Fragment中去訪問另一個Fragment的視圖。
還是在第一節代碼的基礎上修改,首先打開fragment2.xml,在這個佈局裡面添加一個按鈕:
然後打開fragment1.xml,為TextView添加一個id:
接著打開Fragment2.java,添加onActivityCreated方法,並處理按鈕的點擊事件:
現在運行一下程序,並點擊一下fragment2上的按鈕,效果如下圖所示:
我們可以看到,在fragment2中成功獲取到了fragment1中的視圖,並彈出Toast。這是怎麼實現的呢?主要都是通過getActivity這個方法實現的。 getActivity方法可以讓Fragment獲取到關聯的Activity,然後再調用Activity的findViewById方法,就可以獲取到和這個Activity關聯的其它Fragment的視圖了。
-------------------------------------------------------------------------------------------------------------
1.靜態增加Fragment
firstfragment.xml :
MyFirstFragment.java :
package com.demo.fragment;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MyFirstFragment extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.firstfragment, container, false);
return v;
}
}
main.xml
MainActivity.java
package com.demo.fragment;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
2.動態增加Fragment
firstfragment.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/Fragment1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical|center_horizontal"
android:text="My first Fragment !!"
android:textAppearance="?android:attr/textAppearanceLarge" />
MyFirstFragment.java
package com.demo.fragment;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MyFirstFragment extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.firstfragment, container, false);
return v;
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:background="#FFFFFF"
android:text="Main Activity"
android:layout_weight="1"
android:textColor="#0000FF" />
<FrameLayout
android:id="@+id/MainActivityUI"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="2"
android:background="#ff0000" />
</LinearLayout>
MainActivity.java
package com.demo.fragment;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
public class MainActivity extends FragmentActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addFragment();
}
void addFragment() {
// Instantiate a new fragment.
Fragment newFragment = new MyFirstFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(R.id.MainActivityUI, newFragment, "first");
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
}
}
增加一個 Fragment 部分的程式碼在addFragment()中實現,首先建立一個 MyFirstFragment 的實例(Instantiate),在使用getFragmentManager()獲得FragmentTransaction物件,並呼叫 beginTransaction() 開始執行Transaction;
過程中使用FragmentTransaction物件add()的方法將Fragment增加到Activity中。
add()有三個參數,第一個是Fragment的ViewGroup;第二個是Fragment 的實例(Instantiate);第三個是Fragment 的Tag。
一旦FragmentTransaction出現變化,必須要呼叫commit()使之生效。
------------------------------------------------------------------------------------------------------
Fragment間的資料傳遞
我們可以透過FragmentManager中的findFragmentById() 或者 findFragmentByTag() 就可以改變Fragment中所定義的參數或布景元件等。
還有一個常用的類別就是FragmentTransaction,這個類別主要功能是可以在Activity中新增、刪除、修改、查詢 Fragment。
而在FragmentTransaction中有一個addToBackStack()方法,使用這個方法的時機通常是在尚未執行commit()前的UI介面增加到 Back Stack 中,當切到下一個Fragment畫面後可以按下倒退鍵便將上一個UI介面回復
下面就用一個簡單的程式來實作Fragment與Fragment間的資料傳遞。
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<LinearLayout
android:id="@+id/rightLinearLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="2"
android:background="#DEDEEE"
android:orientation="vertical" >
</LinearLayout>
<LinearLayout
android:id="@+id/leftLinearLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#DEEEDE"
android:orientation="vertical" >
</LinearLayout>
</LinearLayout>
fragment1.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fragment1"
android:textColor="#0000FF" />
<Button
android:id="@+id/left_button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="按鍵" />
</LinearLayout>
fragment2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fragment2"
android:textColor="#0000FF" />
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
MainActivity.java
package edu.nkut.fragmenttest;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyFragment1 MyFragment1Ref = new MyFragment1();
MyFragment2 MyFragment2Ref = new MyFragment2();
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.leftLinearLayout, MyFragment1Ref, "leftfragment");
ft.add(R.id.rightLinearLayout, MyFragment2Ref, "rightfragment");
// ft.addToBackStack(null);
ft.commit();
}
}
MyFragment1.java
package edu.nkut.fragmenttest;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
public class MyFragment1 extends Fragment {
private Button button1;
private View view;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment1, container, false);
button1 = (Button) view.findViewById(R.id.left_button1);
button1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Fragment rightFragment = MyFragment1.this.getFragmentManager().findFragmentByTag("rightfragment");
EditText editTextRef = (EditText) rightFragment.getView().findViewById(R.id.editText1);
editTextRef.setText("按下 Fragment1 按鍵");
}
});
return view;
}
}
MyFragment2.java
package edu.nkut.fragmenttest;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MyFragment2 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment2, container, false);
return v;
}
}
上述執行程式時當按下Fragment1的按鍵時,會從Fragment1送一個字串到Fragment2的EditText。以上就完成了Fragment與Fragment間的資料傳遞,程式中在MainActivity.java中可以試試看有無ft.addToBackStack(null)在按下倒退鍵有何差別。
--------------------------------------------------------------------------------
Fragment裡面也可放Fragment :
fragment1.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#00ffff"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is Fragment 1"
android:textColor="#000000"
/>
</LinearLayout>
Fragment1.java:
public class Fragment1 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.fragment1,container,false);
}
}
fragment2.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#00ff00"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is Fragment 2"
android:textColor="#000000"
/>
</LinearLayout>
public class Fragment2 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.fragment2,container,false);
}
}
fragment3.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffff00"
android:orientation="horizontal" >
<FrameLayout
android:id="@+id/fragment1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#ff0000" />
<FrameLayout
android:id="@+id/fragment2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#ff0000" />
</LinearLayout>
Fragment3:
public class Fragment3 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.fragment3,container,false);
}
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Fragment newFragment2 = new Fragment2();
Fragment newFragment1 = new Fragment1();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(R.id.fragment1, newFragment1, "first");
ft.add(R.id.fragment2, newFragment2, "second");
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
}
}
activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout>
MainActivity.java:
public class MainActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Display display = getWindowManager().getDefaultDisplay();
if (display.getWidth() > display.getHeight()) {
Fragment3 fragment3 = new Fragment3();
getSupportFragmentManager().beginTransaction().replace(R.id.main_layout, fragment3).commit();
} else {
Fragment1 fragment1 = new Fragment1();
getSupportFragmentManager().beginTransaction().replace(R.id.main_layout, fragment1).commit();
}
}
}
直向:
橫向:
http://cheng-min-i-taiwan.blogspot.tw/2013/01/fragment.html
http://cheng-min-i-taiwan.blogspot.tw/2012/04/android-fragment-hellofragment.html
我們都知道,Android上的界面展示都是通過Activity實現的,Activity實在是太常用了,我相信大家都已經非常熟悉了,這裡就不再贅述。
但是Activity也有它的局限性,同樣的界面在手機上顯示可能很好看,在平板上就未必了,因為平板的屏幕非常大,手機的界面放在平板上可能會有過分被拉長、控件間距過大等情況。這個時候更好的體驗效果是在Activity中嵌入"小Activity",然後每個"小Activity"又可以擁有自己的佈局。因此,我們今天的主角Fragment登場了。
Fragment初探
為了讓界面可以在平板上更好地展示,Android在3.0版本引入了Fragment(碎片)功能,它非常類似於Activity,可以像Activity一樣包含佈局。 Fragment通常是嵌套在Activity中使用的,現在想像這種場景:有兩個Fragment,Fragment 1包含了一個ListView,每行顯示一本書的標題。 Fragment 2包含了TextView和ImageView,來顯示書的詳細內容和圖片。
如果現在程序運行豎屏模式的平板或手機上,Fragment 1可能嵌入在一個Activity中,而Fragment 2可能嵌入在另一個Activity中,如下圖所示:
由此可以看出,使用Fragment可以讓我們更加充分地利用平板的屏幕空間,下面我們一起來探究下如何使用Fragment。
首先需要注意,Fragment是在3.0版本引入的,如果你使用的是3.0之前的系統,需要先導入android-support-v4的jar包才能使用Fragment功能。
新建一個項目叫做Fragments,然後在layout文件夾下新建一個名為fragment1.xml的佈局文件:
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:background="#00ff00" >
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="This is fragment 1"
- android:textColor="#000000"
- android:textSize="25sp" />
- </LinearLayout>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:background="#ffff00" >
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="This is fragment 2"
- android:textColor="#000000"
- android:textSize="25sp" />
- </LinearLayout>
- public class Fragment1 extends Fragment {
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
- return inflater.inflate(R.layout.fragment1, container, false);
- }
- }
- public class Fragment2 extends Fragment {
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
- return inflater.inflate(R.layout.fragment2, container, false);
- }
- }
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:baselineAligned="false" >
- <fragment
- android:id="@+id/fragment1"
- android:name="com.example.fragmentdemo.Fragment1"
- android:layout_width="0dip"
- android:layout_height="match_parent"
- android:layout_weight="1" />
- <fragment
- android:id="@+id/fragment2"
- android:name="com.example.fragmentdemo.Fragment2"
- android:layout_width="0dip"
- android:layout_height="match_parent"
- android:layout_weight="1" />
- </LinearLayout>
最後打開或新建MainActivity作為程序的主Activity,裡面的代碼非常簡單,都是自動生成的:
- public class MainActivity extends Activity {
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- }
- }
你已經學會瞭如何在XML中使用Fragment,但是這僅僅是Fragment最簡單的功能而已。 Fragment真正的強大之處在於可以動態地添加到Activity當中,因此這也是你必須要掌握的東西。當你學會了在程序運行時向Activity添加Fragment,程序的界面就可以定制的更加多樣化。下面我們立刻來看看,如何動態添加Fragment。
還是在上一節代碼的基礎上修改,打開activity_main.xml,將其中對Fragment的引用都刪除,只保留最外層的LinearLayout,並給它添加一個id,因為我們要動態添加Fragment,不用在XML裡添加了,刪除後代碼如下:
然後打開MainActivity,修改其中的代碼如下所示:
getFragmentManager()是3.0之後 3.0之前請使用getSupportFragmentManager()
Activity 要繼承 FragmentActivity 才能動態加載
首先,我們要獲取屏幕的寬度和高度,然後進行判斷,如果屏幕寬度大於高度就添加fragment1,如果高度大於寬度就添加fragment2。動態添加Fragment主要分為4步:
1.獲取到FragmentManager,在Activity中可以直接通過getFragmentManager得到。
2.開啟一個事務,通過調用beginTransaction方法開啟。
3.向容器內加入Fragment,一般使用replace方法實現,需要傳入容器的id和Fragment的實例。
4.提交事務,調用commit方法提交。
現在運行一下程序,效果如下圖所示:
還是在上一節代碼的基礎上修改,打開activity_main.xml,將其中對Fragment的引用都刪除,只保留最外層的LinearLayout,並給它添加一個id,因為我們要動態添加Fragment,不用在XML裡添加了,刪除後代碼如下:
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/main_layout"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:baselineAligned="false" >
- </LinearLayout>
- public class MainActivity extends Activity {
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- Display display = getWindowManager().getDefaultDisplay();
- if (display.getWidth() > display.getHeight()) {
- Fragment1 fragment1 = new Fragment1();
- getFragmentManager().beginTransaction().replace(R.id.main_layout, fragment1).commit();
- } else {
- Fragment2 fragment2 = new Fragment2();
- getFragmentManager().beginTransaction().replace(R.id.main_layout, fragment2).commit();
- }
- }
- }
getFragmentManager()是3.0之後 3.0之前請使用getSupportFragmentManager()
Activity 要繼承 FragmentActivity 才能動態加載
首先,我們要獲取屏幕的寬度和高度,然後進行判斷,如果屏幕寬度大於高度就添加fragment1,如果高度大於寬度就添加fragment2。動態添加Fragment主要分為4步:
1.獲取到FragmentManager,在Activity中可以直接通過getFragmentManager得到。
2.開啟一個事務,通過調用beginTransaction方法開啟。
3.向容器內加入Fragment,一般使用replace方法實現,需要傳入容器的id和Fragment的實例。
4.提交事務,調用commit方法提交。
現在運行一下程序,效果如下圖所示:
Fragment的生命周期
和Activity一樣,Fragment也有自己的生命週期,理解Fragment的生命週期非常重要,我們通過代碼的方式來瞧一瞧Fragment的生命週期是什麼樣的:
- public class Fragment1 extends Fragment {
- public static final String TAG = "Fragment1";
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
- Log.d(TAG, "onCreateView");
- return inflater.inflate(R.layout.fragment1, container, false);
- }
- @Override
- public void onAttach(Activity activity) {
- super.onAttach(activity);
- Log.d(TAG, "onAttach");
- }
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- Log.d(TAG, "onCreate");
- }
- @Override
- public void onActivityCreated(Bundle savedInstanceState) {
- super.onActivityCreated(savedInstanceState);
- Log.d(TAG, "onActivityCreated");
- }
- @Override
- public void onStart() {
- super.onStart();
- Log.d(TAG, "onStart");
- }
- @Override
- public void onResume() {
- super.onResume();
- Log.d(TAG, "onResume");
- }
- @Override
- public void onPause() {
- super.onPause();
- Log.d(TAG, "onPause");
- }
- @Override
- public void onStop() {
- super.onStop();
- Log.d(TAG, "onStop");
- }
- @Override
- public void onDestroyView() {
- super.onDestroyView();
- Log.d(TAG, "onDestroyView");
- }
- @Override
- public void onDestroy() {
- super.onDestroy();
- Log.d(TAG, "onDestroy");
- }
- @Override
- public void onDetach() {
- super.onDetach();
- Log.d(TAG, "onDetach");
- }
- }
看到這裡,我相信大多數朋友已經非常明白了,因為這和Activity的生命週期太相似了。只是有幾個Activity中沒有的新方法,這裡需要重點介紹一下:
onAttach方法:Fragment和Activity建立關聯的時候調用。
onCreateView方法:為Fragment加載佈局時調用。
onActivityCreated方法:當Activity中的onCreate方法執行完後調用。
onDestroyView方法:Fragment中的佈局被移除時調用。
onDetach方法:Fragment和Activity解除關聯的時候調用。
Fragment之間進行通信
通常情況下,Activity都會包含多個Fragment,這時多個Fragment之間如何進行通信就是個非常重要的問題了。我們通過一個例子來看一下,如何在一個Fragment中去訪問另一個Fragment的視圖。
還是在第一節代碼的基礎上修改,首先打開fragment2.xml,在這個佈局裡面添加一個按鈕:
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical"
- android:background="#ffff00" >
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="This is fragment 2"
- android:textColor="#000000"
- android:textSize="25sp" />
- <Button
- android:id="@+id/button"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Get fragment1 text"
- />
- </LinearLayout>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:background="#00ff00" >
- <TextView
- android:id="@+id/fragment1_text"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="This is fragment 1"
- android:textColor="#000000"
- android:textSize="25sp" />
- </LinearLayout>
- public class Fragment2 extends Fragment {
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
- return inflater.inflate(R.layout.fragment2, container, false);
- }
- @Override
- public void onActivityCreated(Bundle savedInstanceState) {
- super.onActivityCreated(savedInstanceState);
- Button button = (Button) getActivity().findViewById(R.id.button);
- button.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- TextView textView = (TextView) getActivity().findViewById(R.id.fragment1_text);
- Toast.makeText(getActivity(), textView.getText(), Toast.LENGTH_LONG).show();
- }
- });
- }
- }
-------------------------------------------------------------------------------------------------------------
1.靜態增加Fragment
firstfragment.xml :
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/Fragment1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical|center_horizontal"
android:text="My first Fragment !!"
android:textAppearance="?android:attr/textAppearanceLarge" />
MyFirstFragment.java :
package com.demo.fragment;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MyFirstFragment extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.firstfragment, container, false);
return v;
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#FFFFFF"
android:text="Main Activity"
android:textColor="#0000FF" />
<fragment
android:id="@+id/first"
android:name="com.demo.fragment.MyFirstFragment"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="2" />
</LinearLayout>
MainActivity.java
package com.demo.fragment;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
2.動態增加Fragment
firstfragment.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/Fragment1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical|center_horizontal"
android:text="My first Fragment !!"
android:textAppearance="?android:attr/textAppearanceLarge" />
MyFirstFragment.java
package com.demo.fragment;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MyFirstFragment extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.firstfragment, container, false);
return v;
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:background="#FFFFFF"
android:text="Main Activity"
android:layout_weight="1"
android:textColor="#0000FF" />
<FrameLayout
android:id="@+id/MainActivityUI"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="2"
android:background="#ff0000" />
</LinearLayout>
MainActivity.java
package com.demo.fragment;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
public class MainActivity extends FragmentActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addFragment();
}
void addFragment() {
// Instantiate a new fragment.
Fragment newFragment = new MyFirstFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(R.id.MainActivityUI, newFragment, "first");
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
}
}
增加一個 Fragment 部分的程式碼在addFragment()中實現,首先建立一個 MyFirstFragment 的實例(Instantiate),在使用getFragmentManager()獲得FragmentTransaction物件,並呼叫 beginTransaction() 開始執行Transaction;
過程中使用FragmentTransaction物件add()的方法將Fragment增加到Activity中。
add()有三個參數,第一個是Fragment的ViewGroup;第二個是Fragment 的實例(Instantiate);第三個是Fragment 的Tag。
一旦FragmentTransaction出現變化,必須要呼叫commit()使之生效。
------------------------------------------------------------------------------------------------------
Fragment間的資料傳遞
我們可以透過FragmentManager中的findFragmentById() 或者 findFragmentByTag() 就可以改變Fragment中所定義的參數或布景元件等。
還有一個常用的類別就是FragmentTransaction,這個類別主要功能是可以在Activity中新增、刪除、修改、查詢 Fragment。
而在FragmentTransaction中有一個addToBackStack()方法,使用這個方法的時機通常是在尚未執行commit()前的UI介面增加到 Back Stack 中,當切到下一個Fragment畫面後可以按下倒退鍵便將上一個UI介面回復
下面就用一個簡單的程式來實作Fragment與Fragment間的資料傳遞。
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<LinearLayout
android:id="@+id/rightLinearLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="2"
android:background="#DEDEEE"
android:orientation="vertical" >
</LinearLayout>
<LinearLayout
android:id="@+id/leftLinearLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#DEEEDE"
android:orientation="vertical" >
</LinearLayout>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fragment1"
android:textColor="#0000FF" />
<Button
android:id="@+id/left_button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="按鍵" />
</LinearLayout>
fragment2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fragment2"
android:textColor="#0000FF" />
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
MainActivity.java
package edu.nkut.fragmenttest;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyFragment1 MyFragment1Ref = new MyFragment1();
MyFragment2 MyFragment2Ref = new MyFragment2();
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.leftLinearLayout, MyFragment1Ref, "leftfragment");
ft.add(R.id.rightLinearLayout, MyFragment2Ref, "rightfragment");
// ft.addToBackStack(null);
ft.commit();
}
}
MyFragment1.java
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
public class MyFragment1 extends Fragment {
private Button button1;
private View view;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment1, container, false);
button1 = (Button) view.findViewById(R.id.left_button1);
button1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Fragment rightFragment = MyFragment1.this.getFragmentManager().findFragmentByTag("rightfragment");
EditText editTextRef = (EditText) rightFragment.getView().findViewById(R.id.editText1);
editTextRef.setText("按下 Fragment1 按鍵");
}
});
return view;
}
}
package edu.nkut.fragmenttest;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MyFragment2 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment2, container, false);
return v;
}
}
--------------------------------------------------------------------------------
Fragment裡面也可放Fragment :
fragment1.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#00ffff"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is Fragment 1"
android:textColor="#000000"
/>
</LinearLayout>
public class Fragment1 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.fragment1,container,false);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#00ff00"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is Fragment 2"
android:textColor="#000000"
/>
</LinearLayout>
Fragment2.java:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.fragment2,container,false);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffff00"
android:orientation="horizontal" >
<FrameLayout
android:id="@+id/fragment1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#ff0000" />
<FrameLayout
android:id="@+id/fragment2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#ff0000" />
</LinearLayout>
Fragment3:
public class Fragment3 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.fragment3,container,false);
}
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Fragment newFragment2 = new Fragment2();
Fragment newFragment1 = new Fragment1();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(R.id.fragment1, newFragment1, "first");
ft.add(R.id.fragment2, newFragment2, "second");
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout>
MainActivity.java:
public class MainActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Display display = getWindowManager().getDefaultDisplay();
if (display.getWidth() > display.getHeight()) {
Fragment3 fragment3 = new Fragment3();
getSupportFragmentManager().beginTransaction().replace(R.id.main_layout, fragment3).commit();
} else {
Fragment1 fragment1 = new Fragment1();
getSupportFragmentManager().beginTransaction().replace(R.id.main_layout, fragment1).commit();
}
}
}
橫向:
訂閱:
文章 (Atom)