天天看點

Android--Fragment基本介紹

版權聲明:本文為部落客原創文章,轉載請标明出處。 https://blog.csdn.net/chaoyu168/article/details/51191389

Android是在Android 3.0 (API level 11)開始引入Fragment的。

  可以把Fragment想成Activity中的子產品,這個子產品有自己的布局,有自己的生命周期,單獨處理自己的輸入,在Activity運作的時候可以加載或者移除Fragment子產品。

  可以把Fragment設計成可以在多個Activity中複用的子產品。

  當開發的應用程式同時适用于平闆電腦和手機時,可以利用Fragment實作靈活的布局,改善使用者體驗。

  如圖:

Android--Fragment基本介紹

Fragment的生命周期

  因為Fragment必須嵌入在Acitivity中使用,是以Fragment的生命周期和它所在的Activity是密切相關的。

  如果Activity是暫停狀态,其中所有的Fragment都是暫停狀态;如果Activity是stopped狀态,這個Activity中所有的Fragment都不能被啟動;如果Activity被銷毀,那麼它其中的所有Fragment都會被銷毀。

  但是,當Activity在活動狀态,可以獨立控制Fragment的狀态,比如加上或者移除Fragment。

  當這樣進行fragment transaction(轉換)的時候,可以把fragment放入Activity的back stack中,這樣使用者就可以進行傳回操作。

Android--Fragment基本介紹

可以看到Fragment比Activity多了幾個額外的生命周期回調方法:

onAttach(Activity)

當Fragment與Activity發生關聯時調用。

onCreateView(LayoutInflater, ViewGroup,Bundle)

建立該Fragment的視圖

onActivityCreated(Bundle)

當Activity的onCreate方法傳回時調用

onDestoryView()

與onCreateView想對應,當該Fragment的視圖被移除時調用

onDetach()

與onAttach相對應,當Fragment與Activity關聯被取消時調用

注意:除了onCreateView,其他的所有方法如果你重寫了,必須調用父類對于該方法的實作,

3、靜态的使用Fragment

嘿嘿,終于到使用的時刻了~~

這是使用Fragment最簡單的一種方式,把Fragment當成普通的控件,直接寫在Activity的布局檔案中。步驟:

1、繼承Fragment,重寫onCreateView決定Fragemnt的布局

2、在Activity中聲明此Fragment,就當和普通的View一樣

下面展示一個例子(我使用2個Fragment作為Activity的布局,一個Fragment用于标題布局,一個Fragment用于内容布局):

TitleFragment的布局檔案:

[html] 

view

plain

copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="45dp"  
  5.     android:background="@drawable/title_bar" >  
  6.     <ImageButton  
  7.         android:id="@+id/id_title_left_btn"  
  8.         android:layout_width="wrap_content"  
  9.         android:layout_height="wrap_content"  
  10.         android:layout_centerVertical="true"  
  11.         android:layout_marginLeft="3dp"  
  12.         android:background="@drawable/showleft_selector" />  
  13.     <TextView  
  14.         android:layout_width="fill_parent"  
  15.         android:layout_height="fill_parent"  
  16.         android:gravity="center"  
  17.         android:text="我不是微信"  
  18.         android:textColor="#fff"  
  19.         android:textSize="20sp"  
  20.         android:textStyle="bold" />  
  21. </RelativeLayout>  

TitleFragment

[java] 

  1. package com.zhy.zhy_fragments;  
  2. import android.app.Fragment;  
  3. import android.os.Bundle;  
  4. import android.view.LayoutInflater;  
  5. import android.view.View;  
  6. import android.view.View.OnClickListener;  
  7. import android.view.ViewGroup;  
  8. import android.widget.ImageButton;  
  9. import android.widget.Toast;  
  10. public class TitleFragment extends Fragment  
  11. {  
  12.     private ImageButton mLeftMenu;  
  13.     @Override  
  14.     public View onCreateView(LayoutInflater inflater, ViewGroup container,  
  15.             Bundle savedInstanceState)  
  16.     {  
  17.         View view = inflater.inflate(R.layout.fragment_title, container, false);  
  18.         mLeftMenu = (ImageButton) view.findViewById(R.id.id_title_left_btn);  
  19.         mLeftMenu.setOnClickListener(new OnClickListener()  
  20.         {  
  21.             @Override  
  22.             public void onClick(View v)  
  23.             {  
  24.                 Toast.makeText(getActivity(),  
  25.                         "i am an ImageButton in TitleFragment ! ",  
  26.                         Toast.LENGTH_SHORT).show();  
  27.             }  
  28.         });  
  29.         return view;  
  30.     }  
  31. }  

同理還有ContentFragment的其布局檔案:

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     android:layout_height="match_parent"  
  3.     android:orientation="vertical" >  
  4.         android:text="使用Fragment做主面闆"  
  5. </LinearLayout>  
  1. public class ContentFragment extends Fragment  
  2.         return inflater.inflate(R.layout.fragment_content, container, false);  

MainActivity

  1. import android.app.Activity;  
  2. import android.view.Window;  
  3. public class MainActivity extends Activity  
  4.     protected void onCreate(Bundle savedInstanceState)  
  5.         super.onCreate(savedInstanceState);  
  6.         requestWindowFeature(Window.FEATURE_NO_TITLE);  
  7.         setContentView(R.layout.activity_main);  

Activity的布局檔案:

  1.     xmlns:tools="http://schemas.android.com/tools"  
  2.     android:layout_height="match_parent" >  
  3.     <fragment  
  4.         android:id="@+id/id_fragment_title"  
  5.         android:name="com.zhy.zhy_fragments.TitleFragment"  
  6.         android:layout_height="45dp" />  
  7.         android:layout_below="@id/id_fragment_title"  
  8.         android:id="@+id/id_fragment_content"  
  9.         android:name="com.zhy.zhy_fragments.ContentFragment"  
  10.         android:layout_height="fill_parent" />  

是不是把Fragment當成普通的View一樣聲明在Activity的布局檔案中,然後所有控件的事件處理等代碼都由各自的Fragment去處理,瞬間覺得Activity好幹淨有木有~~代碼的可讀性、複用性以及可維護性是不是瞬間提升了~~~下面看下效果圖:

4、動态的使用Fragment

上面已經示範了,最簡單的使用Fragment的方式~下面介紹如何動态的添加、更新、以及删除Fragment

為了動态使用Fragment,我們修改一下Actvity的布局檔案,中間使用一個FrameLayout,下面添加四個按鈕~~~嘿嘿~~不是微信的按鈕- -!

  1.     <include  
  2.         android:id="@+id/id_ly_bottombar"  
  3.         android:layout_height="55dp"  
  4.         android:layout_alignParentBottom="true"  
  5.         layout="@layout/bottombar" />  
  6.     <FrameLayout  
  7.         android:id="@+id/id_content"  
  8.         android:layout_above="@id/id_ly_bottombar"  
  9.         android:layout_below="@id/id_fragment_title" />  

底部四個按鈕的布局就不貼了,到時看效果圖就明白了~~

下面主Activity

  1. import android.app.FragmentManager;  
  2. import android.app.FragmentTransaction;  
  3. import android.widget.LinearLayout;  
  4. public class MainActivity extends Activity implements OnClickListener  
  5.     private LinearLayout mTabWeixin;  
  6.     private LinearLayout mTabFriend;  
  7.     private ContentFragment mWeixin;  
  8.     private FriendFragment mFriend;  
  9.         // 初始化控件和聲明事件  
  10.         mTabWeixin = (LinearLayout) findViewById(R.id.tab_bottom_weixin);  
  11.         mTabFriend = (LinearLayout) findViewById(R.id.tab_bottom_friend);  
  12.         mTabWeixin.setOnClickListener(this);  
  13.         mTabFriend.setOnClickListener(this);  
  14.         // 設定預設的Fragment  
  15.         setDefaultFragment();  
  16.     private void setDefaultFragment()  
  17.         FragmentManager fm = getFragmentManager();  
  18.         FragmentTransaction transaction = fm.beginTransaction();  
  19.         mWeixin = new ContentFragment();  
  20.         transaction.replace(R.id.id_content, mWeixin);  
  21.         transaction.commit();  
  22.     public void onClick(View v)  
  23.         // 開啟Fragment事務  
  24.         switch (v.getId())  
  25.         case R.id.tab_bottom_weixin:  
  26.             if (mWeixin == null)  
  27.                 mWeixin = new ContentFragment();  
  28.             // 使用目前Fragment的布局替代id_content的控件  
  29.             transaction.replace(R.id.id_content, mWeixin);  
  30.             break;  
  31.         case R.id.tab_bottom_friend:  
  32.             if (mFriend == null)  
  33.                 mFriend = new FriendFragment();  
  34.             transaction.replace(R.id.id_content, mFriend);  
  35.         }  
  36.         // transaction.addToBackStack();  
  37.         // 事務送出  

可以看到我們使用FragmentManager對Fragment進行了動态的加載,這裡使用的是replace方法~~下一節我會詳細介紹FragmentManager的常用API。

注:如果使用Android3.0以下的版本,需要引入v4的包,然後Activity繼承FragmentActivity,然後通過getSupportFragmentManager獲得FragmentManager。不過還是建議版Menifest檔案的uses-sdk的minSdkVersion和targetSdkVersion都改為11以上,這樣就不必引入v4包了。

代碼中間還有兩個Fragment的子類,ContentFragment上面已經見過,FriendFragment其實類似:

  1. public class FriendFragment extends Fragment  
  2.         return inflater.inflate(R.layout.fragment_friend, container, false);  

效果圖:

可以看到很好的實作了效果,其實這個效果以前的部落格中也出現過,在部落格:

Android項目Tab類型主界面大總結 Fragment+TabPageIndicator+ViewPager

,有興趣可以看看。ps:為了代碼的簡潔,就不添加按鈕的點選變化什麼的了,主要講解功能了~~~

5、Fragment家族常用的API

Fragment常用的三個類:

android.app.Fragment 主要用于定義Fragment

android.app.FragmentManager 主要用于在Activity中操作Fragment

android.app.FragmentTransaction 保證一些列Fragment操作的原子性,熟悉事務這個詞,一定能明白~

a、擷取FragmentManage的方式:

getFragmentManager() // v4中,getSupportFragmentManager

b、主要的操作都是FragmentTransaction的方法

FragmentTransaction transaction = fm.benginTransatcion();//開啟一個事務

transaction.add() 

往Activity中添加一個Fragment

transaction.remove()

從Activity中移除一個Fragment,如果被移除的Fragment沒有添加到回退棧(回退棧後面會詳細說),這個Fragment執行個體将會被銷毀。

transaction.replace()

使用另一個Fragment替換目前的,實際上就是remove()然後add()的合體~

transaction.hide()

隐藏目前的Fragment,僅僅是設為不可見,并不會銷毀

transaction.show()

顯示之前隐藏的Fragment

detach()

會将view從UI中移除,和remove()不同,此時fragment的狀态依然由FragmentManager維護。

attach()

重建view視圖,附加到UI上并顯示。

transatcion.commit()//送出一個事務

注意:常用Fragment的哥們,可能會經常遇到這樣Activity狀态不一緻:State loss這樣的錯誤。主要是因為:commit方法一定要在Activity.onSaveInstance()之前調用。

上述,基本是操作Fragment的所有的方式了,在一個事務開啟到送出可以進行多個的添加、移除、替換等操作。

值得注意的是:如果你喜歡使用Fragment,一定要清楚這些方法,哪個會銷毀視圖,哪個會銷毀執行個體,哪個僅僅隻是隐藏,這樣才能更好的使用它們。

a、比如:我在FragmentA中的EditText填了一些資料,當切換到FragmentB時,如果希望會到A還能看到資料,則适合你的就是hide和show;也就是說,希望保留使用者操作的面闆,你可以使用hide和show,當然了不要使勁在那new執行個體,進行下非null判斷。

b、再比如:我不希望保留使用者操作,你可以使用remove(),然後add();或者使用replace()這個和remove,add是相同的效果。

c、remove和detach有一點細微的差別,在不考慮回退棧的情況下,remove會銷毀整個Fragment執行個體,而detach則隻是銷毀其視圖結構,執行個體并不會被銷毀。那麼二者怎麼取舍使用呢?如果你的目前Activity一直存在,那麼在不希望保留使用者操作的時候,你可以優先使用detach。

上述已經介紹完成了Fragment常用的一些方法,相信看完,大家一定清楚了Fragment的産生理由,以及如何使用Fragment,再根據API的講解,也能明白,曾經為何覺得Fragment會出現一些列亂七八槽的問題,終究是因為沒有弄清楚其生命周期。

由于篇幅原因,剩下的内容留到下一篇了。在下一篇,會介紹:

1、如何管理Fragment回退棧

2、Fragment如何與Activity互動

3、Fragment與Activity互動的最佳實踐

4、沒有視圖的Fragment的用處

5、使用Fragment建立對話框

6、如何與ActionBar,MenuItem內建等

參考:

http://blog.csdn.net/lmj623565791/article/details/37970961

繼續閱讀