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

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

生活随笔

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

Android

Android Fragment 深度解析

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

有過(guò)一些面試經(jīng)驗(yàn)的人基本都深有體會(huì),每次面試一般都會(huì)問(wèn)到Fragment的知識(shí),所以,今天我就單獨(dú)把Fragment拿出來(lái)與大家分享一下.

會(huì)涉及到Fragment如何產(chǎn)生,什么是Fragment,Fragment生命周期,如何靜態(tài)和動(dòng)態(tài)使用Fragment,Fragment回退棧,Fragment事務(wù),以及Fragment的一些特殊用途,例如:沒(méi)有布局的Fragment有何用處?Fragment如何與Activiy交互?Fragment如何創(chuàng)建對(duì)話框?Fragment如何與ActionBar集成等等...

1、Fragment的產(chǎn)生與介紹


Android運(yùn)行在各種各樣的設(shè)備中,有小屏幕的手機(jī),超大屏的平板甚至電視。針對(duì)屏幕尺寸的差距,很多情況下,都是先針對(duì)手機(jī)開(kāi)發(fā)一套app,然后拷貝一份,修改布局以適應(yīng)什么超級(jí)大屏的。難道無(wú)法做到一個(gè)app可以同時(shí)適應(yīng)手機(jī)和平板嗎?答案是,當(dāng)然有,那就是Fragment.Fragment出現(xiàn)的初衷就是為了解決這樣的問(wèn)題。

你可以把Fragment當(dāng)成Activity一個(gè)界面的一部分,甚至Activity的界面由完全不同的Fragment組成,更帥氣的是Fragment有自己的聲明周期和接收、處理用戶的事件,這樣就不必要在一個(gè)Activity里面寫(xiě)一堆事件、控件的代碼了。更為重要的是,你可以動(dòng)態(tài)的添加、替換、移除某個(gè)Fragment。

2、Fragment的生命周期

Fragment必須是依存于Activity而存在的,因此Activity的生命周期會(huì)直接影響到Fragment的生命周期。官網(wǎng)這張圖很好的說(shuō)明了倆者的關(guān)系:

  

可以看到Fragment比Activity多了幾個(gè)額外的生命周期回調(diào)函數(shù):

onAttach(Activity);  //當(dāng)Activity與Fragment發(fā)生關(guān)聯(lián)時(shí)調(diào)用

onCreateView(LayoutInflater,ViewGroup,Bundle);  //創(chuàng)建該Fragment的視圖

onActivityCreate(bundle);  //當(dāng)Activity的onCreate();方法返回時(shí)調(diào)用

onDestoryView();  //與onCreateView相對(duì)應(yīng),當(dāng)改Fragment被移除時(shí)調(diào)用

onDetach();  //與onAttach()相對(duì)應(yīng),當(dāng)Fragment與Activity的關(guān)聯(lián)被取消時(shí)調(diào)用

注意:除了onCreateView,其他的所有方法如果你重寫(xiě)了,必須調(diào)用父類(lèi)對(duì)于該方法的實(shí)現(xiàn)。

3、靜態(tài)的使用Fragment

接下來(lái),就是實(shí)踐的時(shí)候了,要注意了,開(kāi)始寫(xiě)代碼嘍~~~~

這是使用Fragment最簡(jiǎn)單的一種方式,把Fragment當(dāng)成普通的控件,直接寫(xiě)在Activity的布局文件中,用布局文件調(diào)用Fragment。

步驟:

1、繼承Fragment,重寫(xiě)onCreateView決定Fragment布局。

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

下面展示一個(gè)例子(我使用倆個(gè)Fragment作為Activity的布局,一個(gè)Fragment用于標(biāo)題布局,一個(gè)Fragment用于內(nèi)容布局)。

TitleFragment的布局文件,在這里我們可以看出,我們可以每個(gè)Fragment當(dāng)中進(jìn)行單獨(dú)的布局:

<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent"android:layout_height="45dp"android:background="@drawable/title_bar" ><ImageButtonandroid:id="@+id/id_title_left_btn"android:layout_width="wrap_content"android:layout_height="fill_parent"android:layout_centerVertical="true"android:background="@drawable/showleft_selector" /><TextViewandroid:layout_width="fill_parent"android:layout_height="fill_parent"android:gravity="center"android:text="我不是微信"android:textColor="#fff"android:textSize="20sp"android:textStyle="bold" /></RelativeLayout>

TitleFragment.java文件,在這里我們能夠看到,可以在各個(gè)Fragment當(dāng)中進(jìn)行獨(dú)立的初始化空間并且處理按鈕之類(lèi)的事件,減輕了Activity的負(fù)擔(dān),我們?cè)贏ctivity中就沒(méi)有必要寫(xiě)一大推初始化控件和事件響應(yīng)的代碼了,這樣就使我們的代碼看上去更加的簡(jiǎn)潔了,可讀性大大提高了。

public class TitleFragment extends Fragment {private ImageButton mButton;@SuppressLint("NewApi")@Overridepublic 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() {@Overridepublic void onClick(View v) {Toast.makeText(getActivity(), "i am an ImageButton in TitleFragment ! ", Toast.LENGTH_SHORT).show(); }});return view;}}

同理還有ContentFragment的布局文件content_fragment.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" ><TextViewandroid:layout_width="fill_parent"android:layout_height="fill_parent"android:gravity="center"android:text="使用Fragment做主面板"android:textSize="20sp"android:textStyle="bold" /></LinearLayout>

同理還有ContentFragment.java文件

public class ContentFragment extends Fragment {@Overridepublic 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 {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main); } }

activity_main.xml文件,在這里我們可以看到,我們把Fragment就當(dāng)做普通的控件一樣,在xml文件中使用。

<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"tools:context="com.example.staticfragment.MainActivity" ><fragment android:name="com.example.staticfragment.TitleFragment"android:id="@+id/title"android:layout_height="45dp"android:layout_width="match_parent"/><fragment android:layout_below="@id/title"android:name="com.example.staticfragment.ContentFragment"android:id="@+id/content"android:layout_height="fill_parent" android:layout_width="fill_parent"/></RelativeLayout>

運(yùn)行效果截圖如下:

注:由于時(shí)間原因,就沒(méi)有上傳源碼,如果需要demo源碼的話,可以留言,我單獨(dú)發(fā)你一下...

4、動(dòng)態(tài)的使用Fragment

上面已經(jīng)演示了最簡(jiǎn)單的使用Fragment的方式,下面分享一下如何動(dòng)態(tài)的添加、更新、以及刪除Fragment。

?首先是,MainActivity的布局文件activity_main.xml,該文件布局文件上面的頂部是一個(gè)TitleFragment,是一個(gè)靜態(tài)聲明的Fragment。

中間也是一個(gè)Fragment,但是這個(gè)Fragment是動(dòng)態(tài)使用的。

最下面是四個(gè)按鈕。用include標(biāo)簽包含外部的布局文件進(jìn)來(lái)的。

<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" ><fragmentandroid:id="@+id/id_fragment_title"android:name="com.example.dynamicfragment.TitleFragment"android:layout_width="fill_parent"android:layout_height="45dp" /><includeandroid:id="@+id/id_ly_bottombar"android:layout_width="fill_parent"android:layout_height="55dp"android:layout_alignParentBottom="true"layout="@layout/bottombar" /><FrameLayoutandroid: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" /></RelativeLayout>

然后是,MainActivity.java文件。也是我們這個(gè)demo當(dāng)中最重要的代碼文件,首先是將上面的布局文件通過(guò)setContentView()加載進(jìn)來(lái).然后是通過(guò)setDefaultFragment();將默認(rèn)的ContentFragment動(dòng)態(tài)的加載進(jìn)來(lái)。接下來(lái)就是通過(guò)我們?cè)谧钕旅娣乐沟乃膫€(gè)按鈕可以隨意的動(dòng)態(tài)切換Fragment。這也是為什么Fragment會(huì)有如此火的原因吧~~~^^

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;@Overrideprotected 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);// 設(shè)置默認(rèn)的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")@Overridepublic void onClick(View v) {FragmentManager fm = getFragmentManager();// 開(kāi)啟Fragment事務(wù)FragmentTransaction transaction = fm.beginTransaction();switch (v.getId()) {case R.id.weixin:if (mWeiXinFragment == null) {mWeiXinFragment = new ContentFragment();}// 使用當(dāng)前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();// 事務(wù)提交 transaction.commit();} }

從上面的代碼,我們可以看出,我們可以使用FragmentManager對(duì)Fragment進(jìn)行動(dòng)態(tài)的加載,這里使用的replace方法~~~下一節(jié)我們會(huì)詳細(xì)的介紹FragmentManager的常用API。。。。^^

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

代碼的中間有倆個(gè)動(dòng)態(tài)加載進(jìn)來(lái)的Fragment,這個(gè)和靜態(tài)使用ragment的聲明方式是一樣的,寫(xiě)一個(gè)繼承Fragment的類(lèi),然后設(shè)置相應(yīng)的布局,由于時(shí)間的關(guān)系,我這里只寫(xiě)了倆個(gè)Fragment,現(xiàn)在把這倆個(gè)的代碼頁(yè)貼出來(lái):

第一個(gè)Fragment和他相應(yīng)的布局文件:

public class ContentFragment extends Fragment {@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_content, 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" > <TextView android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="center" android:text="weixin" android:textSize="20sp" android:textStyle="bold" /> </LinearLayout>

第二個(gè)Fragment和他相應(yīng)的布局文件:

public class FriendFragment extends Fragment {@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_friend, 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" > <TextView android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="center" android:text="friend" android:textSize="20sp" android:textStyle="bold" /> </LinearLayout>

好了,現(xiàn)在基本的代碼都有了,我們把demo的運(yùn)行圖貼出來(lái)給大家分享一下(注:時(shí)間原因,沒(méi)注意布局以及圖片的美化,只是功能的實(shí)現(xiàn)),這是分別點(diǎn)擊下面第一個(gè)和第二個(gè)按鈕的效果圖,從而實(shí)現(xiàn)了中間用一個(gè)Fragment動(dòng)態(tài)的加載這倆個(gè)Fragment的顯示。

?? ? ? ??

ps:為了代碼的簡(jiǎn)潔,就不添加按鈕的點(diǎn)擊變化什么的了,主要講解功能了~~~

?

5、Fragment常用的API:

Fragment常用的三個(gè)類(lèi):

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

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

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

a、獲取FragmentManage的方式:

getFragmentManager() // v4中,getSupportFragmentManager

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

FragmentTransaction transaction = fm.benginTransatcion();//開(kāi)啟一個(gè)事務(wù)

transaction.add()?

往Activity中添加一個(gè)Fragment

transaction.remove()

從Activity中移除一個(gè)Fragment,如果被移除的Fragment沒(méi)有添加到回退棧(回退棧后面會(huì)詳細(xì)說(shuō)),這個(gè)Fragment實(shí)例將會(huì)被銷(xiāo)毀。

transaction.replace()

使用另一個(gè)Fragment替換當(dāng)前的,實(shí)際上就是remove()然后add()的合體~

transaction.hide()

隱藏當(dāng)前的Fragment,僅僅是設(shè)為不可見(jiàn),并不會(huì)銷(xiāo)毀

transaction.show()

顯示之前隱藏的Fragment

detach()

將此Fragment從Activity中分離,會(huì)銷(xiāo)毀其布局,但不會(huì)銷(xiāo)毀該實(shí)例

attach()

將從Activity中分離的Fragment,重新關(guān)聯(lián)到該Activity,重新創(chuàng)建其視圖層次

transatcion.commit()//提交一個(gè)事務(wù)

注意:常用Fragment的哥們,可能會(huì)經(jīng)常遇到這樣Activity狀態(tài)不一致:State loss這樣的錯(cuò)誤。主要是因?yàn)?#xff1a;commit方法一定要在Activity.onSaveInstance()之前調(diào)用。

上述,基本是操作Fragment的所有的方式了,在一個(gè)事務(wù)開(kāi)啟到提交可以進(jìn)行多個(gè)的添加、移除、替換等操作。

值得注意的是:如果你喜歡使用Fragment,一定要清楚這些方法,哪個(gè)會(huì)銷(xiāo)毀視圖,哪個(gè)會(huì)銷(xiāo)毀實(shí)例,哪個(gè)僅僅只是隱藏,這樣才能更好的使用它們。

a、比如:我在FragmentA中的EditText填了一些數(shù)據(jù),當(dāng)切換到FragmentB時(shí),如果希望會(huì)到A還能看到數(shù)據(jù),則適合你的就是hide和show;也就是說(shuō),希望保留用戶操作的面板,你可以使用hide和show,當(dāng)然了不要使勁在那new實(shí)例,進(jìn)行下非null判斷。

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

c、remove和detach有一點(diǎn)細(xì)微的區(qū)別,在不考慮回退棧的情況下,remove會(huì)銷(xiāo)毀整個(gè)Fragment實(shí)例,而detach則只是銷(xiāo)毀其視圖結(jié)構(gòu),實(shí)例并不會(huì)被銷(xiāo)毀。那么二者怎么取舍使用呢?如果你的當(dāng)前Activity一直存在,那么在不希望保留用戶操作的時(shí)候,你可以?xún)?yōu)先使用detach。

上述已經(jīng)介紹完成了Fragment常用的一些方法,相信看完,大家一定清楚了Fragment的產(chǎn)生理由,以及如何使用Fragment,再根據(jù)API的講解,也能明白,曾經(jīng)為何覺(jué)得Fragment會(huì)出現(xiàn)一些列亂七八槽的問(wèn)題,終究是因?yàn)闆](méi)有弄清楚其生命周期。

由于篇幅原因,剩下的內(nèi)容留到下一篇了。在下一篇,會(huì)介紹:

1、如何管理Fragment回退棧

2、Fragment如何與Activity交互

3、Fragment與Activity交互的最佳實(shí)踐

4、沒(méi)有視圖的Fragment的用處

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

6、如何與ActionBar,MenuItem集成等~~

總結(jié)

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

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