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