Android Fragment使用全解
我們都知道,Android上的界面展示都是通過Activity實(shí)現(xiàn)的,Activity實(shí)在是太常用了,我相信大家都已經(jīng)非常熟悉了,這里就不再贅述。
但是Activity也有它的局限性,同樣的界面在手機(jī)上顯示可能很好看,在平板上就未必了,因?yàn)槠桨宓钠聊环浅4?,手機(jī)的界面放在平板上可能會(huì)有過分被拉長、控件間距過大等情況。這個(gè)時(shí)候更好的體驗(yàn)效果是在Activity中嵌入"小Activity",然后每個(gè)"小Activity"又可以擁有自己的布局。因此,我們今天的主角Fragment登場了。
Fragment初探
為了讓界面可以在平板上更好地展示,Android在3.0版本引入了Fragment(碎片)功能,它非常類似于Activity,可以像Activity一樣包含布局。Fragment通常是嵌套在Activity中使用的,現(xiàn)在想象這種場景:有兩個(gè)Fragment,F(xiàn)ragment 1包含了一個(gè)ListView,每行顯示一本書的標(biāo)題。Fragment 2包含了TextView和ImageView,來顯示書的詳細(xì)內(nèi)容和圖片。
如果現(xiàn)在程序運(yùn)行豎屏模式的平板或手機(jī)上,F(xiàn)ragment 1可能嵌入在一個(gè)Activity中,而Fragment 2可能嵌入在另一個(gè)Activity中,如下圖所示:
而如果現(xiàn)在程序運(yùn)行在橫屏模式的平板上,兩個(gè)Fragment就可以嵌入在同一個(gè)Activity中了,如下圖所示:
由此可以看出,使用Fragment可以讓我們更加充分地利用平板的屏幕空間,下面我們一起來探究下如何使用Fragment。
首先需要注意,F(xiàn)ragment是在3.0版本引入的,如果你使用的是3.0之前的系統(tǒng),需要先導(dǎo)入android-support-v4的jar包才能使用Fragment功能。
新建一個(gè)項(xiàng)目叫做Fragments,然后在layout文件夾下新建一個(gè)名為fragment1.xml的布局文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#00ff00" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="This is fragment 1" android:textColor="#000000" android:textSize="25sp" /> </LinearLayout>
可以看到,這個(gè)布局文件非常簡單,只有一個(gè)LinearLayout,里面加入了一個(gè)TextView。我們?nèi)绶ㄅ谥圃傩陆ㄒ粋€(gè)fragment2.xml :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ffff00" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="This is fragment 2" android:textColor="#000000" android:textSize="25sp" /> </LinearLayout>
然后新建一個(gè)類Fragment1,這個(gè)類是繼承自Fragment的:
public class Fragment1 extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment1, container, false); } }
我們可以看到,這個(gè)類也非常簡單,主要就是加載了我們剛剛寫好的fragment1.xml布局文件并返回。同樣的方法,我們再寫好Fragment2 :
public class Fragment2 extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment2, container, false); } }
然后打開或新建activity_main.xml作為主Activity的布局文件,在里面加入兩個(gè)Fragment的引用,使用android:name前綴來引用具體的Fragment:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:baselineAligned="false" > <fragment android:id="@+id/fragment1" android:name="com.example.fragmentdemo.Fragment1" android:layout_width="0dip" android:layout_height="match_parent" android:layout_weight="1" /> <fragment android:id="@+id/fragment2" android:name="com.example.fragmentdemo.Fragment2" android:layout_width="0dip" android:layout_height="match_parent" android:layout_weight="1" /> </LinearLayout>
最后打開或新建MainActivity作為程序的主Activity,里面的代碼非常簡單,都是自動(dòng)生成的:
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }
現(xiàn)在我們來運(yùn)行一次程序,就會(huì)看到,一個(gè)Activity很融洽地包含了兩個(gè)Fragment,這兩個(gè)Fragment平分了整個(gè)屏幕,效果圖如下:
動(dòng)態(tài)添加Fragment
你已經(jīng)學(xué)會(huì)了如何在XML中使用Fragment,但是這僅僅是Fragment最簡單的功能而已。Fragment真正的強(qiáng)大之處在于可以動(dòng)態(tài)地添加到Activity當(dāng)中,因此這也是你必須要掌握的東西。當(dāng)你學(xué)會(huì)了在程序運(yùn)行時(shí)向Activity添加Fragment,程序的界面就可以定制的更加多樣化。下面我們立刻來看看,如何動(dòng)態(tài)添加Fragment。
還是在上一節(jié)代碼的基礎(chǔ)上修改,打開activity_main.xml,將其中對Fragment的引用都刪除,只保留最外層的LinearLayout,并給它添加一個(gè)id,因?yàn)槲覀円獎(jiǎng)討B(tài)添加Fragment,不用在XML里添加了,刪除后代碼如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/main_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:baselineAligned="false" > </LinearLayout>
然后打開MainActivity,修改其中的代碼如下所示:
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Display display = getWindowManager().getDefaultDisplay(); if (display.getWidth() > display.getHeight()) { Fragment1 fragment1 = new Fragment1(); getFragmentManager().beginTransaction().replace(R.id.main_layout, fragment1).commit(); } else { Fragment2 fragment2 = new Fragment2(); getFragmentManager().beginTransaction().replace(R.id.main_layout, fragment2).commit(); } } }
首先,我們要獲取屏幕的寬度和高度,然后進(jìn)行判斷,如果屏幕寬度大于高度就添加fragment1,如果高度大于寬度就添加fragment2。動(dòng)態(tài)添加Fragment主要分為4步:
1.獲取到FragmentManager,在Activity中可以直接通過getFragmentManager得到。
2.開啟一個(gè)事務(wù),通過調(diào)用beginTransaction方法開啟。
3.向容器內(nèi)加入Fragment,一般使用replace方法實(shí)現(xiàn),需要傳入容器的id和Fragment的實(shí)例。
4.提交事務(wù),調(diào)用commit方法提交。
現(xiàn)在運(yùn)行一下程序,效果如下圖所示:
如果你是在使用模擬器運(yùn)行,按下ctrl + F11切換到豎屏模式。效果如下圖所示:
Fragment的生命周期
和Activity一樣,F(xiàn)ragment也有自己的生命周期,理解Fragment的生命周期非常重要,我們通過代碼的方式來瞧一瞧Fragment的生命周期是什么樣的:
public class Fragment1 extends Fragment { public static final String TAG = "Fragment1"; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log.d(TAG, "onCreateView"); return inflater.inflate(R.layout.fragment1, container, false); } @Override public void onAttach(Activity activity) { super.onAttach(activity); Log.d(TAG, "onAttach"); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d(TAG, "onCreate"); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); Log.d(TAG, "onActivityCreated"); } @Override public void onStart() { super.onStart(); Log.d(TAG, "onStart"); } @Override public void onResume() { super.onResume(); Log.d(TAG, "onResume"); } @Override public void onPause() { super.onPause(); Log.d(TAG, "onPause"); } @Override public void onStop() { super.onStop(); Log.d(TAG, "onStop"); } @Override public void onDestroyView() { super.onDestroyView(); Log.d(TAG, "onDestroyView"); } @Override public void onDestroy() { super.onDestroy(); Log.d(TAG, "onDestroy"); } @Override public void onDetach() { super.onDetach(); Log.d(TAG, "onDetach"); } }
可以看到,上面的代碼在每個(gè)生命周期的方法里都打印了日志,然后我們來運(yùn)行一下程序,可以看到打印日志如下:
這時(shí)點(diǎn)擊一下home鍵,打印日志如下:
如果你再重新進(jìn)入進(jìn)入程序,打印日志如下:
然后點(diǎn)擊back鍵退出程序,打印日志如下:
看到這里,我相信大多數(shù)朋友已經(jīng)非常明白了,因?yàn)檫@和Activity的生命周期太相似了。只是有幾個(gè)Activity中沒有的新方法,這里需要重點(diǎn)介紹一下:
- onAttach方法:Fragment和Activity建立關(guān)聯(lián)的時(shí)候調(diào)用。
- onCreateView方法:為Fragment加載布局時(shí)調(diào)用。
- onActivityCreated方法:當(dāng)Activity中的onCreate方法執(zhí)行完后調(diào)用。
- onDestroyView方法:Fragment中的布局被移除時(shí)調(diào)用。
- onDetach方法:Fragment和Activity解除關(guān)聯(lián)的時(shí)候調(diào)用。
Fragment之間進(jìn)行通信
通常情況下,Activity都會(huì)包含多個(gè)Fragment,這時(shí)多個(gè)Fragment之間如何進(jìn)行通信就是個(gè)非常重要的問題了。我們通過一個(gè)例子來看一下,如何在一個(gè)Fragment中去訪問另一個(gè)Fragment的視圖。
還是在第一節(jié)代碼的基礎(chǔ)上修改,首先打開fragment2.xml,在這個(gè)布局里面添加一個(gè)按鈕:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:background="#ffff00" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="This is fragment 2" android:textColor="#000000" android:textSize="25sp" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Get fragment1 text" /> </LinearLayout>
然后打開fragment1.xml,為TextView添加一個(gè)id:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#00ff00" > <TextView android:id="@+id/fragment1_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="This is fragment 1" android:textColor="#000000" android:textSize="25sp" /> </LinearLayout>
接著打開Fragment2.java,添加onActivityCreated方法,并處理按鈕的點(diǎn)擊事件:
public class Fragment2 extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment2, container, false); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); Button button = (Button) getActivity().findViewById(R.id.button); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { TextView textView = (TextView) getActivity().findViewById(R.id.fragment1_text); Toast.makeText(getActivity(), textView.getText(), Toast.LENGTH_LONG).show(); } }); } }
現(xiàn)在運(yùn)行一下程序,并點(diǎn)擊一下fragment2上的按鈕,效果如下圖所示:
我們可以看到,在fragment2中成功獲取到了fragment1中的視圖,并彈出Toast。這是怎么實(shí)現(xiàn)的呢?主要都是通過getActivity這個(gè)方法實(shí)現(xiàn)的。getActivity方法可以讓Fragment獲取到關(guān)聯(lián)的Activity,然后再調(diào)用Activity的findViewById方法,就可以獲取到和這個(gè)Activity關(guān)聯(lián)的其它Fragment的視圖了。
以上就是Android Fragment使用全解的詳細(xì)內(nèi)容,更多關(guān)于Android Fragment使用的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Android仿拉手網(wǎng)團(tuán)購App我的收藏界面實(shí)例代碼
這篇文章主要介紹了Android仿拉手團(tuán)購網(wǎng)App我的收藏界面實(shí)例代碼,需要的朋友可以參考下2017-05-05Android中g(shù)oogle Zxing實(shí)現(xiàn)二維碼與條形碼掃描
這篇文章主要介紹了Android中g(shù)oogle Zxing實(shí)現(xiàn)二維碼與條形碼掃描的相關(guān)資料,需要的朋友可以參考下2017-05-05Android 獲取IP地址的實(shí)現(xiàn)方法
這篇文章主要介紹了Android 獲取IP地址的實(shí)現(xiàn)方法的相關(guān)資料,這里提供了具體實(shí)現(xiàn)的方法及代碼,使用WIFI 和GPRS的思路,需要的朋友可以參考下2016-11-11Android自定義view Path 的高級用法之搜索按鈕動(dòng)畫
這篇文章主要介紹了Android自定義view Path 的高級用法之搜索按鈕動(dòng)畫,需要的朋友可以參考下2017-06-06Flutter學(xué)習(xí)之Navigator的高級用法分享
這篇文章主要為大家詳細(xì)介紹了Flutter中之Navigator的高級用法的相關(guān)知識(shí),文中的示例代碼講解詳細(xì),具有一定的學(xué)習(xí)價(jià)值,感興趣的可以了解一下2023-02-02詳解Android開發(fā)數(shù)據(jù)持久化之文件存儲(chǔ)(附源碼)
本篇文章主要介紹了詳解Android開發(fā)數(shù)據(jù)持久化之文件存儲(chǔ)(附源碼),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-03-03Android自定義processor實(shí)現(xiàn)bindView功能的實(shí)例
下面小編就為大家分享一篇Android自定義processor實(shí)現(xiàn)bindView功能的實(shí)例,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2017-12-12Android仿微信底部菜單欄功能顯示未讀消息數(shù)量
這篇文章主要介紹了Android仿微信底部菜單欄功能,并顯示未讀消息數(shù)量,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-05-05Android開發(fā)之使用GridView展示圖片的方法
這篇文章主要介紹了Android開發(fā)之使用GridView展示圖片的方法,涉及Android使用GridView操作圖片的布局與圖片調(diào)用功能實(shí)現(xiàn)技巧,需要的朋友可以參考下2016-01-01