日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 运维知识 > Android >内容正文

Android

Android Fragment 真正的完全解析(下)

發(fā)布時(shí)間:2025/6/15 Android 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Android Fragment 真正的完全解析(下) 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

本篇將介紹上篇博客提到的:如何管理Fragment回退棧,Fragment如何與Activity交互,Fragment與Activity交互的最佳實(shí)踐,沒(méi)有視圖的Fragment的用處,使用Fragment創(chuàng)建對(duì)話框,如何與ActionBar,MenuItem集成等~~

1、管理Fragment回退棧

類似與Android系統(tǒng)為Activity維護(hù)一個(gè)任務(wù)棧,我們也可以通過(guò)Activity維護(hù)一個(gè)回退棧來(lái)保存每次Fragment事務(wù)發(fā)生的變化。如果你將Fragment任務(wù)添加到回退棧,當(dāng)用戶點(diǎn)擊后退按鈕時(shí),將看到上一次的保存的Fragment。一旦Fragment完全從后退棧中彈出,用戶再次點(diǎn)擊后退鍵,則退出當(dāng)前Activity。

看這樣一個(gè)效果圖:


點(diǎn)擊第一個(gè)按鈕,切換到第二個(gè)界面,點(diǎn)擊第二個(gè)按鈕,切換到第三個(gè)界面,然后點(diǎn)擊Back鍵依次回退。這像不像初學(xué)Android時(shí)的Activity跳轉(zhuǎn),當(dāng)然了,這里肯定不是,不然我就跪了。這里是Fragment實(shí)現(xiàn)的,用戶點(diǎn)擊Back,實(shí)際是Fragment回退棧不斷的彈棧。

如何添加一個(gè)Fragment事務(wù)到回退棧:

FragmentTransaction.addToBackStack(String)

下面講解代碼:很明顯一共是3個(gè)Fragment和一個(gè)Activity.

先看Activity的布局文件:

[html] view plaincopy
  • <RelativeLayout?xmlns:android="http://schemas.android.com/apk/res/android"??
  • ????xmlns:tools="http://schemas.android.com/tools"??
  • ????android:layout_width="match_parent"??
  • ????android:layout_height="match_parent"?>??
  • ??
  • ????<FrameLayout??
  • ????????android:id="@+id/id_content"??
  • ????????android:layout_width="fill_parent"??
  • ????????android:layout_height="fill_parent"?>??
  • ????</FrameLayout>??
  • ??
  • </RelativeLayout>??
  • 不同的Fragment就在這個(gè)FrameLayout中顯示。

    MainActivity.java

    [java] view plaincopy
  • package?com.zhy.zhy_fragments;??
  • ??
  • import?android.app.Activity;??
  • import?android.app.FragmentManager;??
  • import?android.app.FragmentTransaction;??
  • import?android.os.Bundle;??
  • import?android.view.Window;??
  • ??
  • public?class?MainActivity?extends?Activity??
  • {??
  • ??
  • ??
  • ????@Override??
  • ????protected?void?onCreate(Bundle?savedInstanceState)??
  • ????{??
  • ????????super.onCreate(savedInstanceState);??
  • ????????requestWindowFeature(Window.FEATURE_NO_TITLE);??
  • ????????setContentView(R.layout.activity_main);??
  • ??
  • ????????FragmentManager?fm?=?getFragmentManager();??
  • ????????FragmentTransaction?tx?=?fm.beginTransaction();??
  • ????????tx.add(R.id.id_content,?new?FragmentOne(),"ONE");??
  • ????????tx.commit();??
  • ????}??
  • ??
  • }??
  • 很簡(jiǎn)單,直接將FragmentOne添加到布局文件中的FrameLayout中,注意這里并沒(méi)有調(diào)用FragmentTransaction.addToBackStack(String),因?yàn)槲也幌矚g在當(dāng)前顯示時(shí),點(diǎn)擊Back鍵出現(xiàn)白板。而是正確的相應(yīng)Back鍵,即退出我們的Activity.

    下面是FragmentOne

    [java] view plaincopy
  • package?com.zhy.zhy_fragments;??
  • ??
  • import?android.app.Fragment;??
  • import?android.app.FragmentManager;??
  • import?android.app.FragmentTransaction;??
  • 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;??
  • ??
  • public?class?FragmentOne?extends?Fragment?implements?OnClickListener??
  • {??
  • ??
  • ????private?Button?mBtn;??
  • ??
  • ????@Override??
  • ????public?View?onCreateView(LayoutInflater?inflater,?ViewGroup?container,??
  • ????????????Bundle?savedInstanceState)??
  • ????{??
  • ????????View?view?=?inflater.inflate(R.layout.fragment_one,?container,?false);??
  • ????????mBtn?=?(Button)?view.findViewById(R.id.id_fragment_one_btn);??
  • ????????mBtn.setOnClickListener(this);??
  • ????????return?view;??
  • ????}??
  • ??
  • ????@Override??
  • ????public?void?onClick(View?v)??
  • ????{??
  • ????????FragmentTwo?fTwo?=?new?FragmentTwo();??
  • ????????FragmentManager?fm?=?getFragmentManager();??
  • ????????FragmentTransaction?tx?=?fm.beginTransaction();??
  • ????????tx.replace(R.id.id_content,?fTwo,?"TWO");??
  • ????????tx.addToBackStack(null);??
  • ????????tx.commit();??
  • ??
  • ????}??
  • ??
  • }??

  • 我們?cè)邳c(diǎn)擊FragmentOne中的按鈕時(shí),使用了replace方法,如果你看了前一篇博客,一定記得replace是remove和add的合體,并且如果不添加事務(wù)到回退棧,前一個(gè)Fragment實(shí)例會(huì)被銷毀。這里很明顯,我們調(diào)用tx.addToBackStack(null);將當(dāng)前的事務(wù)添加到了回退棧,所以FragmentOne實(shí)例不會(huì)被銷毀,但是視圖層次依然會(huì)被銷毀,即會(huì)調(diào)用onDestoryView和onCreateView,證據(jù)就是:仔細(xì)看上面的效果圖,我們?cè)谔D(zhuǎn)前在文本框輸入的內(nèi)容,在用戶Back得到第一個(gè)界面的時(shí)候不見(jiàn)了。

    接下來(lái)FragmentTwo

    [java] view plaincopy
  • package?com.zhy.zhy_fragments;??
  • ??
  • import?android.app.Fragment;??
  • import?android.app.FragmentManager;??
  • import?android.app.FragmentTransaction;??
  • 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;??
  • ??
  • public?class?FragmentTwo?extends?Fragment?implements?OnClickListener??
  • {??
  • ??
  • ????private?Button?mBtn?;??
  • ????@Override??
  • ????public?View?onCreateView(LayoutInflater?inflater,?ViewGroup?container,??
  • ????????????Bundle?savedInstanceState)??
  • ????{??
  • ????????View?view?=?inflater.inflate(R.layout.fragment_two,?container,?false);??
  • ????????mBtn?=?(Button)?view.findViewById(R.id.id_fragment_two_btn);??
  • ????????mBtn.setOnClickListener(this);??
  • ????????return?view?;???
  • ????}??
  • ????@Override??
  • ????public?void?onClick(View?v)??
  • ????{??
  • ????????FragmentThree?fThree?=?new?FragmentThree();??
  • ????????FragmentManager?fm?=?getFragmentManager();??
  • ????????FragmentTransaction?tx?=?fm.beginTransaction();??
  • ????????tx.hide(this);??
  • ????????tx.add(R.id.id_content?,?fThree,?"THREE");??
  • //??????tx.replace(R.id.id_content,?fThree,?"THREE");??
  • ????????tx.addToBackStack(null);??
  • ????????tx.commit();??
  • ????}??
  • ??
  • ??
  • }??

  • 這里點(diǎn)擊時(shí),我們沒(méi)有使用replace,而是先隱藏了當(dāng)前的Fragment,然后添加了FragmentThree的實(shí)例,最后將事務(wù)添加到回退棧。這樣做的目的是為了給大家提供一種方案:如果不希望視圖重繪該怎么做,請(qǐng)?jiān)俅巫屑?xì)看效果圖,我們?cè)贔ragmentTwo的EditText填寫的內(nèi)容,用戶Back回來(lái)時(shí),數(shù)據(jù)還在~~~

    最后FragmentThree就是簡(jiǎn)單的Toast了:

    [java] view plaincopy
  • package?com.zhy.zhy_fragments;??
  • ??
  • 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.Toast;??
  • ??
  • public?class?FragmentThree?extends?Fragment?implements?OnClickListener??
  • {??
  • ??
  • ????private?Button?mBtn;??
  • ??
  • ????@Override??
  • ????public?View?onCreateView(LayoutInflater?inflater,?ViewGroup?container,??
  • ????????????Bundle?savedInstanceState)??
  • ????{??
  • ????????View?view?=?inflater.inflate(R.layout.fragment_three,?container,?false);??
  • ????????mBtn?=?(Button)?view.findViewById(R.id.id_fragment_three_btn);??
  • ????????mBtn.setOnClickListener(this);??
  • ????????return?view;??
  • ????}??
  • ??
  • ????@Override??
  • ????public?void?onClick(View?v)??
  • ????{??
  • ????????Toast.makeText(getActivity(),?"?i?am?a?btn?in?Fragment?three",??
  • ????????????????Toast.LENGTH_SHORT).show();??
  • ????}??
  • ??
  • }??

  • 好了,經(jīng)過(guò)上面的介紹,應(yīng)該已經(jīng)知道Fragment回退棧是怎么一回事了,以及hide,replace等各自的應(yīng)用的場(chǎng)景。

    這里極其注意一點(diǎn):上面的整體代碼不具有任何參考價(jià)值,純粹為了顯示回退棧,在后面講解了Fragment與Activity通信以后,會(huì)重構(gòu)上面的代碼!

    2、Fragment與Activity通信

    因?yàn)樗械腇ragment都是依附于Activity的,所以通信起來(lái)并不復(fù)雜,大概歸納為:

    a、如果你Activity中包含自己管理的Fragment的引用,可以通過(guò)引用直接訪問(wèn)所有的Fragment的public方法

    b、如果Activity中未保存任何Fragment的引用,那么沒(méi)關(guān)系,每個(gè)Fragment都有一個(gè)唯一的TAG或者ID,可以通過(guò)getFragmentManager.findFragmentByTag()或者findFragmentById()獲得任何Fragment實(shí)例,然后進(jìn)行操作。

    c、在Fragment中可以通過(guò)getActivity得到當(dāng)前綁定的Activity的實(shí)例,然后進(jìn)行操作。

    注:如果在Fragment中需要Context,可以通過(guò)調(diào)用getActivity(),如果該Context需要在Activity被銷毀后還存在,則使用getActivity().getApplicationContext()。

    3、Fragment與Activity通信的最佳實(shí)踐

    因?yàn)橐紤]Fragment的重復(fù)使用,所以必須降低Fragment與Activity的耦合,而且Fragment更不應(yīng)該直接操作別的Fragment,畢竟Fragment操作應(yīng)該由它的管理者Activity來(lái)決定。

    下面我通過(guò)兩種方式的代碼,分別重構(gòu),FragmentOne和FragmentTwo的點(diǎn)擊事件,以及Activity對(duì)點(diǎn)擊事件的響應(yīng):

    首先看FragmentOne

    [java] view plaincopy
  • package?com.zhy.zhy_fragments;??
  • ??
  • 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;??
  • ??
  • public?class?FragmentOne?extends?Fragment?implements?OnClickListener??
  • {??
  • ????private?Button?mBtn;??
  • ??
  • ????/**?
  • ?????*?設(shè)置按鈕點(diǎn)擊的回調(diào)?
  • ?????*?@author?zhy?
  • ?????*?
  • ?????*/??
  • ????public?interface?FOneBtnClickListener??
  • ????{??
  • ????????void?onFOneBtnClick();??
  • ????}??
  • ??
  • ????@Override??
  • ????public?View?onCreateView(LayoutInflater?inflater,?ViewGroup?container,??
  • ????????????Bundle?savedInstanceState)??
  • ????{??
  • ????????View?view?=?inflater.inflate(R.layout.fragment_one,?container,?false);??
  • ????????mBtn?=?(Button)?view.findViewById(R.id.id_fragment_one_btn);??
  • ????????mBtn.setOnClickListener(this);??
  • ????????return?view;??
  • ????}??
  • ??
  • ????/**?
  • ?????*?交給宿主Activity處理,如果它希望處理?
  • ?????*/??
  • ????@Override??
  • ????public?void?onClick(View?v)??
  • ????{??
  • ????????if?(getActivity()?instanceof?FOneBtnClickListener)??
  • ????????{??
  • ????????????((FOneBtnClickListener)?getActivity()).onFOneBtnClick();??
  • ????????}??
  • ????}??
  • ??
  • }??

  • 可以看到現(xiàn)在的FragmentOne不和任何Activity耦合,任何Activity都可以使用;并且我們聲明了一個(gè)接口,來(lái)回調(diào)其點(diǎn)擊事件,想要管理其點(diǎn)擊事件的Activity實(shí)現(xiàn)此接口就即可??梢钥吹轿覀?cè)趏nClick中首先判斷了當(dāng)前綁定的Activity是否實(shí)現(xiàn)了該接口,如果實(shí)現(xiàn)了則調(diào)用。

    再看FragmentTwo

    [java] view plaincopy
  • package?com.zhy.zhy_fragments;??
  • ??
  • 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;??
  • ??
  • public?class?FragmentTwo?extends?Fragment?implements?OnClickListener??
  • {??
  • ??
  • ??????
  • ????private?Button?mBtn?;??
  • ??????
  • ????private?FTwoBtnClickListener?fTwoBtnClickListener?;??
  • ??????
  • ????public?interface?FTwoBtnClickListener??
  • ????{??
  • ????????void?onFTwoBtnClick();??
  • ????}??
  • ????//設(shè)置回調(diào)接口??
  • ????public?void?setfTwoBtnClickListener(FTwoBtnClickListener?fTwoBtnClickListener)??
  • ????{??
  • ????????this.fTwoBtnClickListener?=?fTwoBtnClickListener;??
  • ????}??
  • ????@Override??
  • ????public?View?onCreateView(LayoutInflater?inflater,?ViewGroup?container,??
  • ????????????Bundle?savedInstanceState)??
  • ????{??
  • ????????View?view?=?inflater.inflate(R.layout.fragment_two,?container,?false);??
  • ????????mBtn?=?(Button)?view.findViewById(R.id.id_fragment_two_btn);??
  • ????????mBtn.setOnClickListener(this);??
  • ????????return?view?;???
  • ????}??
  • ????@Override??
  • ????public?void?onClick(View?v)??
  • ????{??
  • ????????if(fTwoBtnClickListener?!=?null)??
  • ????????{??
  • ????????????fTwoBtnClickListener.onFTwoBtnClick();??
  • ????????}??
  • ????}??
  • ??
  • }??

  • 與FragmentOne極其類似,但是我們提供了setListener這樣的方法,意味著Activity不僅需要實(shí)現(xiàn)該接口,還必須顯示調(diào)用mFTwo.setfTwoBtnClickListener(this)。

    最后看Activity :

    [java] view plaincopy
  • package?com.zhy.zhy_fragments;??
  • ??
  • import?android.app.Activity;??
  • import?android.app.FragmentManager;??
  • import?android.app.FragmentTransaction;??
  • import?android.os.Bundle;??
  • import?android.view.Window;??
  • ??
  • import?com.zhy.zhy_fragments.FragmentOne.FOneBtnClickListener;??
  • import?com.zhy.zhy_fragments.FragmentTwo.FTwoBtnClickListener;??
  • ??
  • public?class?MainActivity?extends?Activity?implements?FOneBtnClickListener,??
  • ????????FTwoBtnClickListener??
  • {??
  • ??
  • ????private?FragmentOne?mFOne;??
  • ????private?FragmentTwo?mFTwo;??
  • ????private?FragmentThree?mFThree;??
  • ??
  • ????@Override??
  • ????protected?void?onCreate(Bundle?savedInstanceState)??
  • ????{??
  • ????????super.onCreate(savedInstanceState);??
  • ????????requestWindowFeature(Window.FEATURE_NO_TITLE);??
  • ????????setContentView(R.layout.activity_main);??
  • ??
  • ????????mFOne?=?new?FragmentOne();??
  • ????????FragmentManager?fm?=?getFragmentManager();??
  • ????????FragmentTransaction?tx?=?fm.beginTransaction();??
  • ????????tx.add(R.id.id_content,?mFOne,?"ONE");??
  • ????????tx.commit();??
  • ????}??
  • ??
  • ????/**?
  • ?????*?FragmentOne?按鈕點(diǎn)擊時(shí)的回調(diào)?
  • ?????*/??
  • ????@Override??
  • ????public?void?onFOneBtnClick()??
  • ????{??
  • ??
  • ????????if?(mFTwo?==?null)??
  • ????????{??
  • ????????????mFTwo?=?new?FragmentTwo();??
  • ????????????mFTwo.setfTwoBtnClickListener(this);??
  • ????????}??
  • ????????FragmentManager?fm?=?getFragmentManager();??
  • ????????FragmentTransaction?tx?=?fm.beginTransaction();??
  • ????????tx.replace(R.id.id_content,?mFTwo,?"TWO");??
  • ????????tx.addToBackStack(null);??
  • ????????tx.commit();??
  • ????}??
  • ??
  • ????/**?
  • ?????*?FragmentTwo?按鈕點(diǎn)擊時(shí)的回調(diào)?
  • ?????*/??
  • ????@Override??
  • ????public?void?onFTwoBtnClick()??
  • ????{??
  • ????????if?(mFThree?==?null)??
  • ????????{??
  • ????????????mFThree?=?new?FragmentThree();??
  • ??
  • ????????}??
  • ????????FragmentManager?fm?=?getFragmentManager();??
  • ????????FragmentTransaction?tx?=?fm.beginTransaction();??
  • ????????tx.hide(mFTwo);??
  • ????????tx.add(R.id.id_content,?mFThree,?"THREE");??
  • ????????//?tx.replace(R.id.id_content,?fThree,?"THREE");??
  • ????????tx.addToBackStack(null);??
  • ????????tx.commit();??
  • ????}??
  • ??
  • }??

  • 代碼重構(gòu)結(jié)束,與開(kāi)始的效果一模一樣。上面兩種通信方式都是值得推薦的,隨便選擇一種自己喜歡的。這里再提一下:雖然Fragment和Activity可以通過(guò)getActivity與findFragmentByTag或者findFragmentById,進(jìn)行任何操作,甚至在Fragment里面操作另外的Fragment,但是沒(méi)有特殊理由是絕對(duì)不提倡的。Activity擔(dān)任的是Fragment間類似總線一樣的角色,應(yīng)當(dāng)由它決定Fragment如何操作。另外雖然Fragment不能響應(yīng)Intent打開(kāi),但是Activity可以,Activity可以接收Intent,然后根據(jù)參數(shù)判斷顯示哪個(gè)Fragment。
    4、如何處理運(yùn)行時(shí)配置發(fā)生變化

    運(yùn)行時(shí)配置發(fā)生變化,最常見(jiàn)的就是屏幕發(fā)生旋轉(zhuǎn),如果你不知道如何處理屏幕變化可以參考:Android 屏幕旋轉(zhuǎn) 處理 AsyncTask 和 ProgressDialog 的最佳方案

    這里提一下:很多人覺(jué)得強(qiáng)制設(shè)置屏幕的方向就可以了,但是有一點(diǎn),當(dāng)你的應(yīng)用被至于后臺(tái)(例如用戶點(diǎn)擊了home),長(zhǎng)時(shí)間沒(méi)有返回的時(shí)候,你的應(yīng)用也會(huì)被重新啟動(dòng)。比如上例:如果你把上面的例子你至于FragmentThree界面,然后處于后臺(tái)狀態(tài),長(zhǎng)時(shí)間后你會(huì)發(fā)現(xiàn)當(dāng)你再次通過(guò)home打開(kāi)時(shí),上面FragmentThree與FragmentOne疊加在一起,這就是因?yàn)槟愕腁ctivity重新啟動(dòng),在原來(lái)的FragmentThree上又繪制了一個(gè)FragmentOne。

    好了,下面看一段代碼:

    Activity:

    [java] view plaincopy
  • package?com.zhy.zhy_fragments;??
  • ??
  • import?android.app.Activity;??
  • import?android.app.FragmentManager;??
  • import?android.app.FragmentTransaction;??
  • import?android.os.Bundle;??
  • import?android.view.Window;??
  • ??
  • public?class?MainActivity?extends?Activity??
  • ??
  • {??
  • ????private?FragmentOne?mFOne;??
  • ??
  • ????@Override??
  • ????protected?void?onCreate(Bundle?savedInstanceState)??
  • ????{??
  • ????????super.onCreate(savedInstanceState);??
  • ????????requestWindowFeature(Window.FEATURE_NO_TITLE);??
  • ????????setContentView(R.layout.activity_main);??
  • ??
  • ????????mFOne?=?new?FragmentOne();??
  • ????????FragmentManager?fm?=?getFragmentManager();??
  • ????????FragmentTransaction?tx?=?fm.beginTransaction();??
  • ????????tx.add(R.id.id_content,?mFOne,?"ONE");??
  • ????????tx.commit();??
  • ??
  • ????}??
  • ??
  • }??

  • Fragment [java] view plaincopy
  • package?com.zhy.zhy_fragments;??
  • ??
  • import?android.app.Fragment;??
  • import?android.os.Bundle;??
  • import?android.util.Log;??
  • import?android.view.LayoutInflater;??
  • import?android.view.View;??
  • import?android.view.ViewGroup;??
  • ??
  • public?class?FragmentOne?extends?Fragment??
  • {??
  • ????private?static?final?String?TAG?=?"FragmentOne";??
  • ??
  • ????@Override??
  • ????public?View?onCreateView(LayoutInflater?inflater,?ViewGroup?container,??
  • ????????????Bundle?savedInstanceState)??
  • ????{??
  • ????????Log.e(TAG,?"onCreateView");??
  • ????????View?view?=?inflater.inflate(R.layout.fragment_one,?container,?false);??
  • ????????return?view;??
  • ????}??
  • ??
  • ????@Override??
  • ????public?void?onCreate(Bundle?savedInstanceState)??
  • ????{??
  • ????????//?TODO?Auto-generated?method?stub??
  • ????????super.onCreate(savedInstanceState);??
  • ??
  • ????????Log.e(TAG,?"onCreate");??
  • ????}??
  • ??
  • ????@Override??
  • ????public?void?onDestroyView()??
  • ????{??
  • ????????//?TODO?Auto-generated?method?stub??
  • ????????super.onDestroyView();??
  • ????????Log.e(TAG,?"onDestroyView");??
  • ????}??
  • ??
  • ????@Override??
  • ????public?void?onDestroy()??
  • ????{??
  • ????????//?TODO?Auto-generated?method?stub??
  • ????????super.onDestroy();??
  • ????????Log.e(TAG,?"onDestroy");??
  • ????}??
  • ??
  • }??

  • 很簡(jiǎn)單的代碼,當(dāng)你運(yùn)行之后,不斷的旋轉(zhuǎn)屏幕,你會(huì)發(fā)現(xiàn)每旋轉(zhuǎn)一次屏幕,屏幕上就多了一個(gè)FragmentOne的實(shí)例,并且后臺(tái)log會(huì)打印出許多套生命周期的回調(diào)。

    類似:

    [html] view plaincopy
  • 07-20?08:18:46.651:?E/FragmentOne(1633):?onCreate??
  • 07-20?08:18:46.651:?E/FragmentOne(1633):?onCreate??
  • 07-20?08:18:46.651:?E/FragmentOne(1633):?onCreate??
  • 07-20?08:18:46.681:?E/FragmentOne(1633):?onCreateView??
  • 07-20?08:18:46.831:?E/FragmentOne(1633):?onCreateView??
  • 07-20?08:18:46.891:?E/FragmentOne(1633):?onCreateView??

  • 這是為什么呢,因?yàn)楫?dāng)屏幕發(fā)生旋轉(zhuǎn),Activity發(fā)生重新啟動(dòng),默認(rèn)的Activity中的Fragment也會(huì)跟著Activity重新創(chuàng)建;這樣造成當(dāng)旋轉(zhuǎn)的時(shí)候,本身存在的Fragment會(huì)重新啟動(dòng),然后當(dāng)執(zhí)行Activity的onCreate時(shí),又會(huì)再次實(shí)例化一個(gè)新的Fragment,這就是出現(xiàn)的原因。

    那么如何解決呢:

    其實(shí)通過(guò)檢查onCreate的參數(shù)Bundle savedInstanceState就可以判斷,當(dāng)前是否發(fā)生Activity的重新創(chuàng)建:

    默認(rèn)的savedInstanceState會(huì)存儲(chǔ)一些數(shù)據(jù),包括Fragment的實(shí)例:通過(guò)打印可以看出:

    [java] view plaincopy
  • 07-20?08:23:12.952:?E/FragmentOne(1782):?Bundle[{android:fragments=android.app.FragmentManagerState@40d0b7b8,?android:viewHierarchyState=Bundle[{android:focusedViewId=2131230721,?android:views=android.util.SparseArray@40d0af68}]}]??
  • 所以,我們簡(jiǎn)單改一下代碼,只有在savedInstanceState==null時(shí),才進(jìn)行創(chuàng)建Fragment實(shí)例: [java] view plaincopy
  • package?com.zhy.zhy_fragments;??
  • ??
  • import?android.app.Activity;??
  • import?android.app.FragmentManager;??
  • import?android.app.FragmentTransaction;??
  • import?android.os.Bundle;??
  • import?android.util.Log;??
  • import?android.view.Window;??
  • ??
  • public?class?MainActivity?extends?Activity??
  • ??
  • {??
  • ????private?static?final?String?TAG?=?"FragmentOne";??
  • ????private?FragmentOne?mFOne;??
  • ??
  • ????@Override??
  • ????protected?void?onCreate(Bundle?savedInstanceState)??
  • ????{??
  • ????????super.onCreate(savedInstanceState);??
  • ????????requestWindowFeature(Window.FEATURE_NO_TITLE);??
  • ????????setContentView(R.layout.activity_main);??
  • ??
  • ????????Log.e(TAG,?savedInstanceState+"");??
  • ??????????
  • ????????if(savedInstanceState?==?null)??
  • ????????{??
  • ????????????mFOne?=?new?FragmentOne();??
  • ????????????FragmentManager?fm?=?getFragmentManager();??
  • ????????????FragmentTransaction?tx?=?fm.beginTransaction();??
  • ????????????tx.add(R.id.id_content,?mFOne,?"ONE");??
  • ????????????tx.commit();??
  • ????????}??
  • ??????????
  • ??????????
  • ??
  • ????}??
  • ??
  • }??

  • 現(xiàn)在無(wú)論進(jìn)行多次旋轉(zhuǎn)都只會(huì)有一個(gè)Fragment實(shí)例在Activity中。

    現(xiàn)在還存在一個(gè)問(wèn)題,就是重新繪制時(shí),Fragment發(fā)生重建,原本的數(shù)據(jù)如何保持?

    其實(shí)和Activity類似,Fragment也有onSaveInstanceState的方法,在此方法中進(jìn)行保存數(shù)據(jù),然后在onCreate或者onCreateView或者onActivityCreated進(jìn)行恢復(fù)都可以。

    由于篇幅原因,就不貼測(cè)試代碼了。

    5、Fragmeny與ActionBar和MenuItem集成

    Fragment可以添加自己的MenuItem到Activity的ActionBar或者可選菜單中。

    a、在Fragment的onCreate中調(diào)用 setHasOptionsMenu(true);

    b、然后在Fragment子類中實(shí)現(xiàn)onCreateOptionsMenu

    c、如果希望在Fragment中處理MenuItem的點(diǎn)擊,也可以實(shí)現(xiàn)onOptionsItemSelected;當(dāng)然了Activity也可以直接處理該MenuItem的點(diǎn)擊事件。

    代碼:

    Fragment

    [java] view plaincopy
  • package?com.zhy.zhy_fragments;??
  • ??
  • import?android.app.Fragment;??
  • import?android.os.Bundle;??
  • import?android.view.LayoutInflater;??
  • import?android.view.Menu;??
  • import?android.view.MenuInflater;??
  • import?android.view.MenuItem;??
  • import?android.view.View;??
  • import?android.view.ViewGroup;??
  • import?android.widget.Toast;??
  • ??
  • public?class?FragmentOne?extends?Fragment??
  • {??
  • ??
  • ????@Override??
  • ????public?void?onCreate(Bundle?savedInstanceState)??
  • ????{??
  • ????????super.onCreate(savedInstanceState);??
  • ????????setHasOptionsMenu(true);??
  • ????}??
  • ??
  • ????@Override??
  • ????public?View?onCreateView(LayoutInflater?inflater,?ViewGroup?container,??
  • ????????????Bundle?savedInstanceState)??
  • ????{??
  • ????????View?view?=?inflater.inflate(R.layout.fragment_one,?container,?false);??
  • ????????return?view;??
  • ????}??
  • ??
  • ????@Override??
  • ????public?void?onCreateOptionsMenu(Menu?menu,?MenuInflater?inflater)??
  • ????{??
  • ????????inflater.inflate(R.menu.fragment_menu,?menu);??
  • ????}??
  • ??
  • ????@Override??
  • ????public?boolean?onOptionsItemSelected(MenuItem?item)??
  • ????{??
  • ????????switch?(item.getItemId())??
  • ????????{??
  • ????????case?R.id.id_menu_fra_test:??
  • ????????????Toast.makeText(getActivity(),?"FragmentMenuItem1",?Toast.LENGTH_SHORT).show();??
  • ????????????break;??
  • ????????}??
  • ????????return?true;??
  • ????}??
  • ??
  • }??

  • Activity [java] view plaincopy
  • package?com.zhy.zhy_fragments;??
  • ??
  • import?android.app.Activity;??
  • import?android.app.FragmentManager;??
  • import?android.app.FragmentTransaction;??
  • import?android.os.Bundle;??
  • import?android.util.Log;??
  • import?android.view.Menu;??
  • import?android.view.MenuItem;??
  • import?android.view.Window;??
  • import?android.widget.Toast;??
  • ??
  • public?class?MainActivity?extends?Activity??
  • ??
  • {??
  • ????private?static?final?String?TAG?=?"FragmentOne";??
  • ????private?FragmentOne?mFOne;??
  • ??
  • ????@Override??
  • ????protected?void?onCreate(Bundle?savedInstanceState)??
  • ????{??
  • ????????super.onCreate(savedInstanceState);??
  • ????????requestWindowFeature(Window.FEATURE_NO_TITLE);??
  • ????????setContentView(R.layout.activity_main);??
  • ??
  • ????????Log.e(TAG,?savedInstanceState?+?"");??
  • ??
  • ????????if?(savedInstanceState?==?null)??
  • ????????{??
  • ????????????mFOne?=?new?FragmentOne();??
  • ????????????FragmentManager?fm?=?getFragmentManager();??
  • ????????????FragmentTransaction?tx?=?fm.beginTransaction();??
  • ????????????tx.add(R.id.id_content,?mFOne,?"ONE");??
  • ????????????tx.commit();??
  • ????????}??
  • ??
  • ????}??
  • ??
  • ????@Override??
  • ????public?boolean?onCreateOptionsMenu(Menu?menu)??
  • ????{??
  • ????????super.onCreateOptionsMenu(menu);??
  • ????????getMenuInflater().inflate(R.menu.main,?menu);??
  • ????????return?true;??
  • ????}??
  • ??
  • ????@Override??
  • ????public?boolean?onOptionsItemSelected(MenuItem?item)??
  • ????{??
  • ????????switch?(item.getItemId())??
  • ????????{??
  • ????????case?R.id.action_settings:??
  • ????????????Toast.makeText(this,?"setting",?Toast.LENGTH_SHORT).show();??
  • ????????????return?true;??
  • ????????default:??
  • ????????????//如果希望Fragment自己處理MenuItem點(diǎn)擊事件,一定不要忘了調(diào)用super.xxx??
  • ????????????return?super.onOptionsItemSelected(item);??
  • ????????}??
  • ????}??
  • ??
  • }??

  • 效果圖:

    好了,可以很好的看到,Fragment可以添加MenuItem,也可以自己處理點(diǎn)擊~~~

    6、沒(méi)有布局的Fragment的作用

    沒(méi)有布局文件Fragment實(shí)際上是為了保存,當(dāng)Activity重啟時(shí),保存大量數(shù)據(jù)準(zhǔn)備的

    請(qǐng)參考博客:Android 屏幕旋轉(zhuǎn) 處理 AsyncTask 和 ProgressDialog 的最佳方案

    7、使用Fragment創(chuàng)建對(duì)話框

    這是Google推薦的方式,我也單獨(dú)寫過(guò)博客介紹,請(qǐng)參考:Android 官方推薦 : DialogFragment 創(chuàng)建對(duì)話框


    好了,終于把Fragment相關(guān)的聯(lián)系到一起了,上述基本包含了Fragment所有的用法~~~相信大家如果能夠看完,一定有不少的收獲~~~


    有任何問(wèn)題,歡迎留言~~~

    兩篇結(jié)束,相信你對(duì)Fragment已經(jīng)有了一定的了解,那么在項(xiàng)目中的最佳實(shí)踐是什么呢?請(qǐng)移步:Android Fragment 你應(yīng)該知道的一切


    總結(jié)

    以上是生活随笔為你收集整理的Android Fragment 真正的完全解析(下)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

    如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。