android 學習-Android Fragment 深度解析

來源:互聯網
上載者:User

android 學習-Android Fragment 深度解析

有過一些面試經驗的人基本都深有體會,每次面試一般都會問到Fragment的知識,所以,今天我就單獨把Fragment拿出來與大家分享一下.

會涉及到Fragment如何產生,什麼是Fragment,Fragment生命週期,如何靜態和動態使用Fragment,Fragment回退棧,Fragment事務,以及Fragment的一些特殊用途,例如:沒有布局的Fragment有何用處?Fragment如何與Activiy互動?Fragment如何建立對話方塊?Fragment如何與ActionBar整合等等...

1、Fragment的產生與介紹


Android運行在各種各樣的裝置中,有小螢幕的手機,超大屏的平板甚至電視。針對螢幕尺寸的差距,很多情況下,都是先針對手機開發一套app,然後拷貝一份,修改布局以適應什麼超級大屏的。難道無法做到一個app可以同時適應手機和平板嗎?答案是,當然有,那就是Fragment.Fragment出現的初衷就是為瞭解決這樣的問題。

你可以把Fragment當成Activity一個介面的一部分,甚至Activity的介面由完全不同的Fragment組成,更帥氣的是Fragment有自己的聲明周期和接收、處理使用者的事件,這樣就不必要在一個Activity裡面寫一堆事件、控制項的代碼了。更為重要的是,你可以動態添加、替換、移除某個Fragment。

2、Fragment的生命週期

Fragment必須是依存於Activity而存在的,因此Activity的生命週期會直接影響到Fragment的生命週期。官網這張圖很好的說明了倆者的關係:

  

可以看到Fragment比Activity多了幾個額外的生命週期回呼函數:

onAttach(Activity);  //當Activity與Fragment發生關聯時調用

onCreateView(LayoutInflater,ViewGroup,Bundle);  //建立該Fragment的視圖

onActivityCreate(bundle);  //當Activity的onCreate();方法返回時調用

onDestoryView();  //與onCreateView相對應,當改Fragment被移除時調用

onDetach();  //與onAttach()相對應,當Fragment與Activity的關聯被取消時調用

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

3、靜態使用Fragment

接下來,就是實踐的時候了,要注意了,開始寫代碼嘍~~~~

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

步驟:

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

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

下面展示一個例子(我使用倆個Fragment作為Activity的布局,一個Fragment用於標題布局,一個Fragment用於內容布局)。

TitleFragment的布局檔案,在這裡我們可以看出,我們可以每個Fragment當中進行單獨的布局:

        

TitleFragment.java檔案,在這裡我們能夠看到,可以在各個Fragment當中進行獨立的初始化空間並且處理按鈕之類的事件,減輕了Activity的負擔,我們在Activity中就沒有必要寫一大推初始化控制項和事件響應的代碼了,這樣就使我們的代碼看上去更加的簡潔了,可讀性大大提高了。

public class TitleFragment extends Fragment {    private ImageButton mButton;    @SuppressLint("NewApi")    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container,            Bundle savedInstanceState) {        View view = inflater.inflate(R.layout.title_fragment, container, false);        mButton = (ImageButton)view.findViewById(R.id.id_title_left_btn);        mButton.setOnClickListener(new OnClickListener() {                        @Override            public void onClick(View v) {                Toast.makeText(getActivity(),                          "i am an ImageButton in TitleFragment ! ",                          Toast.LENGTH_SHORT).show();              }        });        return view;    }}

同理還有ContentFragment的布局檔案content_fragment.xml

    

同理還有ContentFragment.java檔案

public class ContentFragment extends Fragment {    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container,            Bundle savedInstanceState) {        return inflater.inflate(R.layout.content_fragment, container,false);    }}

下面就是主Activity以及他的布局檔案

MainActivity.java檔案
public class MainActivity extends Activity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);          requestWindowFeature(Window.FEATURE_NO_TITLE);          setContentView(R.layout.activity_main);      }}

activity_main.xml檔案,在這裡我們可以看到,我們把Fragment就當做普通的控制項一樣,在xml檔案中使用。

              

運行效果如下:

註:由於時間原因,就沒有上傳源碼,如果需要demo源碼的話,可以留言,我單獨發你一下...

4、動態使用Fragment

上面已經示範了最簡單的使用Fragment的方式,下面分享一下如何動態添加、更新、以及刪除Fragment。

首先是,MainActivity的布局檔案activity_main.xml,該檔案布局檔案上面的頂部是一個TitleFragment,是一個靜態聲明的Fragment。

中間也是一個Fragment,但是這個Fragment是動態使用的。

最下面是四個按鈕。用include標籤包含外部的布局檔案進來的。

            <frameLayout        android:id="@+id/id_content"        android:layout_width="fill_parent"        android:layout_height="fill_parent"        android:layout_above="@id/id_ly_bottombar"        android:layout_below="@id/id_fragment_title" />

然後是,MainActivity.java檔案。也是我們這個demo當中最重要的代碼檔案,首先是將上面的布局檔案通過setContentView()載入進來.然後是通過setDefaultFragment();將預設的ContentFragment動態載入進來。接下來就是通過我們在最下面防止的四個按鈕可以隨意的動態切換Fragment。這也是為什麼Fragment會有如此火的原因吧~~~^^

public class MainActivity extends ActionBarActivity implements OnClickListener {    private ImageButton mTabWeixin;    private ImageButton mTabFriend;    private ImageButton mTabDiscover;    private ImageButton mTabMe;    private ContentFragment mWeiXinFragment;    private FriendFragment mFriendFragment;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        requestWindowFeature(Window.FEATURE_NO_TITLE);        setContentView(R.layout.activity_main);        initView();    }    public void initView() {        // 初始化控制項和聲明事件        mTabWeixin = (ImageButton) findViewById(R.id.weixin);        mTabFriend = (ImageButton) findViewById(R.id.friend);        mTabWeixin.setOnClickListener(this);        mTabFriend.setOnClickListener(this);        // 設定預設的Fragment        setDefaultFragment();    }    @SuppressLint("NewApi")    private void setDefaultFragment() {        FragmentManager manager = getFragmentManager();        FragmentTransaction transaction = manager.beginTransaction();        mWeiXinFragment = new ContentFragment();        transaction.replace(R.id.id_content, mWeiXinFragment);        transaction.commit();    }    @SuppressLint("NewApi")    @Override    public void onClick(View v) {        FragmentManager fm = getFragmentManager();        // 開啟Fragment事務        FragmentTransaction transaction = fm.beginTransaction();        switch (v.getId()) {        case R.id.weixin:            if (mWeiXinFragment == null) {                mWeiXinFragment = new ContentFragment();            }            // 使用當前Fragment的布局替代id_content的控制項            transaction.replace(R.id.id_content, mWeiXinFragment);            break;        case R.id.friend:            if (mFriendFragment == null) {                mFriendFragment = new FriendFragment();            }            transaction.replace(R.id.id_content, mFriendFragment);            break;        }        // transaction.addToBackStack();        // 事務提交        transaction.commit();    }}

從上面的代碼,我們可以看出,我們可以使用FragmentManager對Fragment進行動態載入,這裡使用的replace方法~~~下一節我們會詳細的介紹FragmentManager的常用API。。。。^^

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

代碼的中間有倆個動態載入進來的Fragment,這個和靜態使用ragment的聲明方式是一樣的,寫一個繼承Fragment的類,然後設定相應的布局,由於時間的關係,我這裡唯寫了倆個Fragment,現在把這倆個的字碼頁貼出來:

第一個Fragment和他相應的布局檔案:

public class ContentFragment extends Fragment {    @Override      public View onCreateView(LayoutInflater inflater, ViewGroup container,              Bundle savedInstanceState)      {          return inflater.inflate(R.layout.fragment_content, container, false);      }  }
                

第二個Fragment和他相應的布局檔案:

public class FriendFragment extends Fragment {    @Override      public View onCreateView(LayoutInflater inflater, ViewGroup container,              Bundle savedInstanceState)      {          return inflater.inflate(R.layout.fragment_friend, container, false);      }  }
                

好了,現在基本的代碼都有了,我們把demo的運行圖貼出來給大家分享一下(註:時間原因,沒注意布局以及圖片的美化,只是功能的實現),這是分別點擊下面第一個和第二個按鈕的,從而實現了中間用一個Fragment動態載入這倆個Fragment的顯示。

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()

將此Fragment從Activity中分離,會銷毀其布局,但不會銷毀該執行個體

attach()

將從Activity中分離的Fragment,重新關聯到該Activity,重新建立其視圖層次

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整合等~~

原創文章by 萌萌的it人 www.itmmd.com

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.