Android Fragment完全解析,關於碎片你所需知道的一切

轉載請註明出處:http://blog.csdn.net/guolin_blog/article/details/8881711

我們都知道,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就可以嵌入在同一個Activity中了,如下圖所示:


由此可以看出,使用Fragment可以讓我們更加充分地利用平板的屏幕空間,下面我們一起來探究下如何使用Fragment。

首先需要注意,Fragment是在3.0版本引入的,如果你使用的是3.0之前的系統,需要先導入android-support-v4的jar包才能使用Fragment功能。

新建一個項目叫做Fragments,然後在layout文件夾下新建一個名爲fragment1.xml的佈局文件:

[html] view plaincopy
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     android:layout_width="match_parent"  
  3.     android:layout_height="match_parent"  
  4.     android:background="#00ff00" >  
  5.   
  6.     <TextView  
  7.         android:layout_width="wrap_content"  
  8.         android:layout_height="wrap_content"  
  9.         android:text="This is fragment 1"  
  10.         android:textColor="#000000"  
  11.         android:textSize="25sp" />  
  12.   
  13. </LinearLayout>  

可以看到,這個佈局文件非常簡單,只有一個LinearLayout,裏面加入了一個TextView。我們如法炮製再新建一個fragment2.xml :

[html] view plaincopy
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     android:layout_width="match_parent"  
  3.     android:layout_height="match_parent"  
  4.     android:background="#ffff00" >  
  5.   
  6.     <TextView  
  7.         android:layout_width="wrap_content"  
  8.         android:layout_height="wrap_content"  
  9.         android:text="This is fragment 2"  
  10.         android:textColor="#000000"  
  11.         android:textSize="25sp" />  
  12.   
  13. </LinearLayout>  

然後新建一個類Fragment1,這個類是繼承自Fragment的:
[java] view plaincopy
  1. public class Fragment1 extends Fragment {  
  2.   
  3.     @Override  
  4.     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {  
  5.         return inflater.inflate(R.layout.fragment1, container, false);  
  6.     }  
  7.   
  8. }  
我們可以看到,這個類也非常簡單,主要就是加載了我們剛剛寫好的fragment1.xml佈局文件並返回。同樣的方法,我們再寫好Fragment2 :
[java] view plaincopy
  1. public class Fragment2 extends Fragment {  
  2.   
  3.     @Override  
  4.     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {  
  5.         return inflater.inflate(R.layout.fragment2, container, false);  
  6.     }  
  7.   
  8. }  
然後打開或新建activity_main.xml作爲主Activity的佈局文件,在裏面加入兩個Fragment的引用,使用android:name前綴來引用具體的Fragment:
[html] view plaincopy
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     android:layout_width="match_parent"  
  3.     android:layout_height="match_parent"  
  4.     android:baselineAligned="false" >  
  5.   
  6.     <fragment  
  7.         android:id="@+id/fragment1"  
  8.         android:name="com.example.fragmentdemo.Fragment1"  
  9.         android:layout_width="0dip"  
  10.         android:layout_height="match_parent"  
  11.         android:layout_weight="1" />  
  12.   
  13.     <fragment  
  14.         android:id="@+id/fragment2"  
  15.         android:name="com.example.fragmentdemo.Fragment2"  
  16.         android:layout_width="0dip"  
  17.         android:layout_height="match_parent"  
  18.         android:layout_weight="1" />  
  19.   
  20. </LinearLayout>  
最後打開或新建MainActivity作爲程序的主Activity,裏面的代碼非常簡單,都是自動生成的:
[java] view plaincopy
  1. public class MainActivity extends Activity {  
  2.   
  3.     @Override  
  4.     protected void onCreate(Bundle savedInstanceState) {  
  5.         super.onCreate(savedInstanceState);  
  6.         setContentView(R.layout.activity_main);  
  7.     }  
  8.   
  9. }  

現在我們來運行一次程序,就會看到,一個Activity很融洽地包含了兩個Fragment,這兩個Fragment平分了整個屏幕,效果圖如下:


動態添加Fragment

你已經學會了如何在XML中使用Fragment,但是這僅僅是Fragment最簡單的功能而已。Fragment真正的強大之處在於可以動態地添加到Activity當中,因此這也是你必須要掌握的東西。當你學會了在程序運行時向Activity添加Fragment,程序的界面就可以定製的更加多樣化。下面我們立刻來看看,如何動態添加Fragment。

還是在上一節代碼的基礎上修改,打開activity_main.xml,將其中對Fragment的引用都刪除,只保留最外層的LinearLayout,並給它添加一個id,因爲我們要動態添加Fragment,不用在XML裏添加了,刪除後代碼如下:

[html] view plaincopy
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     android:id="@+id/main_layout"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:baselineAligned="false" >  
  6.   
  7. </LinearLayout>  
然後打開MainActivity,修改其中的代碼如下所示:
[java] view plaincopy
  1. public class MainActivity extends Activity {  
  2.   
  3.     @Override  
  4.     protected void onCreate(Bundle savedInstanceState) {  
  5.         super.onCreate(savedInstanceState);  
  6.         setContentView(R.layout.activity_main);  
  7.         Display display = getWindowManager().getDefaultDisplay();  
  8.         if (display.getWidth() > display.getHeight()) {  
  9.             Fragment1 fragment1 = new Fragment1();  
  10.             getFragmentManager().beginTransaction().replace(R.id.main_layout, fragment1).commit();  
  11.         } else {  
  12.             Fragment2 fragment2 = new Fragment2();  
  13.             getFragmentManager().beginTransaction().replace(R.id.main_layout, fragment2).commit();  
  14.         }  
  15.     }  
  16.   
  17. }  

首先,我們要獲取屏幕的寬度和高度,然後進行判斷,如果屏幕寬度大於高度就添加fragment1,如果高度大於寬度就添加fragment2。動態添加Fragment主要分爲4步:

1.獲取到FragmentManager,在Activity中可以直接通過getFragmentManager得到。

2.開啓一個事務,通過調用beginTransaction方法開啓。

3.向容器內加入Fragment,一般使用replace方法實現,需要傳入容器的id和Fragment的實例。

4.提交事務,調用commit方法提交。

現在運行一下程序,效果如下圖所示:


如果你是在使用模擬器運行,按下ctrl + F11切換到豎屏模式。效果如下圖所示:

                                

Fragment的生命週期

和Activity一樣,Fragment也有自己的生命週期,理解Fragment的生命週期非常重要,我們通過代碼的方式來瞧一瞧Fragment的生命週期是什麼樣的:

[java] view plaincopy
  1. public class Fragment1 extends Fragment {  
  2.     public static final String TAG = "Fragment1";  
  3.   
  4.     @Override  
  5.     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {  
  6.         Log.d(TAG, "onCreateView");  
  7.         return inflater.inflate(R.layout.fragment1, container, false);  
  8.     }  
  9.   
  10.     @Override  
  11.     public void onAttach(Activity activity) {  
  12.         super.onAttach(activity);  
  13.         Log.d(TAG, "onAttach");  
  14.     }  
  15.   
  16.     @Override  
  17.     public void onCreate(Bundle savedInstanceState) {  
  18.         super.onCreate(savedInstanceState);  
  19.         Log.d(TAG, "onCreate");  
  20.     }  
  21.   
  22.     @Override  
  23.     public void onActivityCreated(Bundle savedInstanceState) {  
  24.         super.onActivityCreated(savedInstanceState);  
  25.         Log.d(TAG, "onActivityCreated");  
  26.     }  
  27.   
  28.     @Override  
  29.     public void onStart() {  
  30.         super.onStart();  
  31.         Log.d(TAG, "onStart");  
  32.     }  
  33.   
  34.     @Override  
  35.     public void onResume() {  
  36.         super.onResume();  
  37.         Log.d(TAG, "onResume");  
  38.     }  
  39.   
  40.     @Override  
  41.     public void onPause() {  
  42.         super.onPause();  
  43.         Log.d(TAG, "onPause");  
  44.     }  
  45.   
  46.     @Override  
  47.     public void onStop() {  
  48.         super.onStop();  
  49.         Log.d(TAG, "onStop");  
  50.     }  
  51.   
  52.     @Override  
  53.     public void onDestroyView() {  
  54.         super.onDestroyView();  
  55.         Log.d(TAG, "onDestroyView");  
  56.     }  
  57.   
  58.     @Override  
  59.     public void onDestroy() {  
  60.         super.onDestroy();  
  61.         Log.d(TAG, "onDestroy");  
  62.     }  
  63.   
  64.     @Override  
  65.     public void onDetach() {  
  66.         super.onDetach();  
  67.         Log.d(TAG, "onDetach");  
  68.     }  
  69.   
  70. }  
可以看到,上面的代碼在每個生命週期的方法裏都打印了日誌,然後我們來運行一下程序,可以看到打印日誌如下:


這時點擊一下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,在這個佈局裏面添加一個按鈕:

[html] view plaincopy
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     android:layout_width="match_parent"  
  3.     android:layout_height="match_parent"  
  4.     android:orientation="vertical"  
  5.     android:background="#ffff00" >  
  6.   
  7.     <TextView  
  8.         android:layout_width="wrap_content"  
  9.         android:layout_height="wrap_content"  
  10.         android:text="This is fragment 2"  
  11.         android:textColor="#000000"  
  12.         android:textSize="25sp" />  
  13.       
  14.     <Button   
  15.         android:id="@+id/button"  
  16.         android:layout_width="wrap_content"  
  17.         android:layout_height="wrap_content"  
  18.         android:text="Get fragment1 text"  
  19.         />  
  20.   
  21. </LinearLayout>  
然後打開fragment1.xml,爲TextView添加一個id:
[html] view plaincopy
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     android:layout_width="match_parent"  
  3.     android:layout_height="match_parent"  
  4.     android:background="#00ff00" >  
  5.   
  6.     <TextView  
  7.         android:id="@+id/fragment1_text"  
  8.         android:layout_width="wrap_content"  
  9.         android:layout_height="wrap_content"  
  10.         android:text="This is fragment 1"  
  11.         android:textColor="#000000"  
  12.         android:textSize="25sp" />  
  13.   
  14. </LinearLayout>  
接着打開Fragment2.java,添加onActivityCreated方法,並處理按鈕的點擊事件:
[java] view plaincopy
  1. public class Fragment2 extends Fragment {  
  2.   
  3.     @Override  
  4.     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {  
  5.         return inflater.inflate(R.layout.fragment2, container, false);  
  6.     }  
  7.   
  8.     @Override  
  9.     public void onActivityCreated(Bundle savedInstanceState) {  
  10.         super.onActivityCreated(savedInstanceState);  
  11.         Button button = (Button) getActivity().findViewById(R.id.button);  
  12.         button.setOnClickListener(new OnClickListener() {  
  13.             @Override  
  14.             public void onClick(View v) {  
  15.                 TextView textView = (TextView) getActivity().findViewById(R.id.fragment1_text);  
  16.                 Toast.makeText(getActivity(), textView.getText(), Toast.LENGTH_LONG).show();  
  17.             }  
  18.         });  
  19.     }  
  20.   
  21. }  
現在運行一下程序,並點擊一下fragment2上的按鈕,效果如下圖所示:


我們可以看到,在fragment2中成功獲取到了fragment1中的視圖,並彈出Toast。這是怎麼實現的呢?主要都是通過getActivity這個方法實現的。getActivity方法可以讓Fragment獲取到關聯的Activity,然後再調用Activity的findViewById方法,就可以獲取到和這個Activity關聯的其它Fragment的視圖了。

好了,以上就是關於Fragment你所須知道的一切。如果想要切身體驗一下Fragment的實戰,請繼續閱讀 Android手機平板兩不誤,使用Fragment實現兼容手機和平板的程序 以及 Android Fragment應用實戰,使用碎片向ActivityGroup說再見 。

發佈了33 篇原創文章 · 獲贊 10 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章