Android Fragment應用實戰 使用碎片向ActivityGroup說再見
現在Fragment的應用真的是越來越廣泛了,之前Android在3.0版本加入Fragment的時候,主要是為了解決Android Pad螢幕比較大,空間不能充分利用的問題,但現在即使只是在手機上,也有很多的場景可以運用到Fragment了,今天我們就來學習其中一個特別棒的應用技巧。
很多手機應用都會有一個非常類似的功能,即螢幕的下方顯示一行Tab標籤選項,點選不同的標籤就可以切換到不同的介面,如以下幾個應用所示:
上面三個應用從左到右分別是QQ、新浪微博和支付寶錢包,可見,這種底部標籤式的佈局策略真的非常常見。
那麼話說回來,這種效果到底是如何的呢?熟悉Android的朋友一定都會知道,很簡單嘛,使用TabHost就OK了!但是殊不知,TabHost並非是那麼的簡單,它的可擴充套件性非常的差,不能隨意地定製Tab項顯示的內容,而且執行還要依賴於ActivityGroup。ActivityGroup原本主要是用於為每一個TabHost的子項管理一個單獨的Activity,但目前已經被廢棄了。為什麼呢?當然就是因為Fragment的出現了!檢視Android官方文件中ActivityGroup的描述,如下所示:
可以看到,在API 13的時候Android就已經將ActivityGroup廢棄掉了,並且官方推薦的替代方式就是使用Fragment,因為它使用起來更加的靈活。那麼剩下的問題就是如何藉助Fragment來完成類似於TabHost一般的效果了,因此我們自然要動起手來了。
在開始之前,首先你必須已經瞭解Fragment的用法了,如果你對Fragment還比較陌生的話,建議先去閱讀我前面的一篇文章 Android Fragment完全解析,關於碎片你所需知道的一切 。
另外,我們還應該準備好程式所需要的資源,比如說每一個Tab項中所用到的圖片。我已經事先從QQ裡截好了幾張圖作為這個專案的資源,稍後會連同原始碼一起給出。
新建一個專案,起名就叫FragmentDemo,這裡我使用的是4.0的API。
下面開始程式設計工作,這裡我們首先需要去編寫一個類似於QQ的主介面,當然只會去編寫介面最下方的TabHost部分,而不會編寫上面的內容介面部分,因為內容介面是應該寫在Fragment的佈局裡的。開啟或新建activity_main.xml作為程式的主佈局檔案,在裡面加入如下程式碼:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height ="match_parent" android:orientation="vertical" > <FrameLayout android:id="@+id/content" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" > </FrameLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="60dp" android:background="@drawable/tab_bg" > <RelativeLayout android:id="@+id/message_layout" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerVertical="true" android:orientation="vertical" > <ImageView android:id="@+id/message_image" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:src="@drawable/message_unselected" /> <TextView android:id="@+id/message_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="訊息" android:textColor="#82858b" /> </LinearLayout> </RelativeLayout> <RelativeLayout android:id="@+id/contacts_layout" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerVertical="true" android:orientation="vertical" > <ImageView android:id="@+id/contacts_image" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:src="@drawable/contacts_unselected" /> <TextView android:id="@+id/contacts_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="聯絡人" android:textColor="#82858b" /> </LinearLayout> </RelativeLayout> <RelativeLayout android:id="@+id/news_layout" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerVertical="true" android:orientation="vertical" > <ImageView android:id="@+id/news_image" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:src="@drawable/news_unselected" /> <TextView android:id="@+id/news_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="動態" android:textColor="#82858b" /> </LinearLayout> </RelativeLayout> <RelativeLayout android:id="@+id/setting_layout" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerVertical="true" android:orientation="vertical" > <ImageView android:id="@+id/setting_image" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:src="@drawable/setting_unselected" /> <TextView android:id="@+id/setting_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="設定" android:textColor="#82858b" /> </LinearLayout> </RelativeLayout> </LinearLayout></LinearLayout>
這段佈局程式碼雖然有點長,但其實主要就分為兩部分。第一個部分就是FrameLayout,這裡只是給FrameLayout的id設定成content,並沒有在裡面新增任何具體的內容,因為具體的內容是要在後面動態進行新增的。第二個部分就是FrameLayout下面的LinearLayout,這個LinearLayout中包含的就是整個類似於TabHost的佈局。可以看到,我們將這個LinearLayout又等分成了四份,每一份中都會顯示一個ImageView和一個TextView。ImageView用於顯示當前Tab的圖示,TextView用於顯示當前Tab的標題,這個效果就會和QQ非常得類似。
既然是等分成了四分,那接下來我們自然要去分別實現四個Fragment和它們的佈局了。新建一個message_layout.xml作為訊息介面的佈局,程式碼如下所示:
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:orientation="vertical" > <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:src="@drawable/message_selected" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:padding="10dp" android:text="這是訊息介面" android:textSize="20sp" /> </LinearLayout></RelativeLayout>
這個佈局就相對簡單多了,只是在螢幕的正中央顯示一個訊息圖示,以及一段文字。
然後要去建立對應這個佈局的Fragment。新建MessageFragment繼承自Fragment,程式碼如下所示:
public class MessageFragment extends Fragment { public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View messageLayout = inflater.inflate(R.layout.message_layout, container, false); return messageLayout; }}
後面就是依葫蘆畫瓢,把其它幾個Fragment以及對應的佈局創建出來。新建contacts_layout.xml作為聯絡人介面的佈局,程式碼如下所示:<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:orientation="vertical" > <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:src="@drawable/contacts_selected" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:padding="10dp" android:text="這是聯絡人介面" android:textSize="20sp" /> </LinearLayout></RelativeLayout>
再新建ContactsFragment繼承自Fragment,程式碼如下所示:public class ContactsFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View contactsLayout = inflater.inflate(R.layout.contacts_layout, container, false); return contactsLayout; }}
然後新建news_layout.xml作為動態介面的佈局,程式碼如下所示:<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:orientation="vertical" > <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:src="@drawable/news_selected" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:padding="10dp" android:text="這是動態介面" android:textSize="20sp" /> </LinearLayout></RelativeLayout>
再新建NewsFragment繼承自Fragment,程式碼如下所示:public class NewsFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View newsLayout = inflater.inflate(R.layout.news_layout, container, false); return newsLayout; }}
最後新建setting_layout.xml作為設定介面的佈局,程式碼如下所示:<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:orientation="vertical" > <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:src="@drawable/setting_selected" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:padding="10dp" android:text="這是設定介面" android:textSize="20sp" /> </LinearLayout></RelativeLayout>
再新建SettingFragment繼承自Fragment,程式碼如下所示:public class SettingFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View settingLayout = inflater.inflate(R.layout.setting_layout, container, false); return settingLayout; }}
這樣我們就把每一個Fragment,以及它們所對應的佈局檔案都建立好了。接下來也就是最關鍵的步驟了,開啟或新建MainActivity作為主Activity,程式碼如下所示:/** * 專案的主Activity,所有的Fragment都嵌入在這裡。 * * @author guolin */public class MainActivity extends Activity implements OnClickListener { /** * 用於展示訊息的Fragment */ private MessageFragment messageFragment; /** * 用於展示聯絡人的Fragment */ private ContactsFragment contactsFragment; /** * 用於展示動態的Fragment */ private NewsFragment newsFragment; /** * 用於展示設定的Fragment */ private SettingFragment settingFragment; /** * 訊息介面佈局 */ private View messageLayout; /** * 聯絡人介面佈局 */ private View contactsLayout; /** * 動態介面佈局 */ private View newsLayout; /** * 設定介面佈局 */ private View settingLayout; /** * 在Tab佈局上顯示訊息圖示的控制元件 */ private ImageView messageImage; /** * 在Tab佈局上顯示聯絡人圖示的控制元件 */ private ImageView contactsImage; /** * 在Tab佈局上顯示動態圖示的控制元件 */ private ImageView newsImage; /** * 在Tab佈局上顯示設定圖示的控制元件 */ private ImageView settingImage; /** * 在Tab佈局上顯示訊息標題的控制元件 */ private TextView messageText; /** * 在Tab佈局上顯示聯絡人標題的控制元件 */ private TextView contactsText; /** * 在Tab佈局上顯示動態標題的控制元件 */ private TextView newsText; /** * 在Tab佈局上顯示設定標題的控制元件 */ private TextView settingText; /** * 用於對Fragment進行管理 */ private FragmentManager fragmentManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main); // 初始化佈局元素 initViews(); fragmentManager = getFragmentManager(); // 第一次啟動時選中第0個tab setTabSelection(0); } /** * 在這裡獲取到每個需要用到的控制元件的例項,並給它們設定好必要的點選事件。 */ private void initViews() { messageLayout = findViewById(R.id.message_layout); contactsLayout = findViewById(R.id.contacts_layout); newsLayout = findViewById(R.id.news_layout); settingLayout = findViewById(R.id.setting_layout); messageImage = (ImageView) findViewById(R.id.message_image); contactsImage = (ImageView) findViewById(R.id.contacts_image); newsImage = (ImageView) findViewById(R.id.news_image); settingImage = (ImageView) findViewById(R.id.setting_image); messageText = (TextView) findViewById(R.id.message_text); contactsText = (TextView) findViewById(R.id.contacts_text); newsText = (TextView) findViewById(R.id.news_text); settingText = (TextView) findViewById(R.id.setting_text); messageLayout.setOnClickListener(this); contactsLayout.setOnClickListener(this); newsLayout.setOnClickListener(this); settingLayout.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.message_layout: // 當點選了訊息tab時,選中第1個tab setTabSelection(0); break; case R.id.contacts_layout: // 當點選了聯絡人tab時,選中第2個tab setTabSelection(1); break; case R.id.news_layout: // 當點選了動態tab時,選中第3個tab setTabSelection(2); break; case R.id.setting_layout: // 當點選了設定tab時,選中第4個tab setTabSelection(3); break; default: break; } } /** * 根據傳入的index引數來設定選中的tab頁。 * * @param index * 每個tab頁對應的下標。0表示訊息,1表示聯絡人,2表示動態,3表示設定。 */ private void setTabSelection(int index) { // 每次選中之前先清楚掉上次的選中狀態 clearSelection(); // 開啟一個Fragment事務 FragmentTransaction transaction = fragmentManager.beginTransaction(); // 先隱藏掉所有的Fragment,以防止有多個Fragment顯示在介面上的情況 hideFragments(transaction); switch (index) { case 0: // 當點選了訊息tab時,改變控制元件的圖片和文字顏色 messageImage.setImageResource(R.drawable.message_selected); messageText.setTextColor(Color.WHITE); if (messageFragment == null) { // 如果MessageFragment為空,則建立一個並新增到介面上 messageFragment = new MessageFragment(); transaction.add(R.id.content, messageFragment); } else { // 如果MessageFragment不為空,則直接將它顯示出來 transaction.show(messageFragment); } break; case 1: // 當點選了聯絡人tab時,改變控制元件的圖片和文字顏色 contactsImage.setImageResource(R.drawable.contacts_selected); contactsText.setTextColor(Color.WHITE); if (contactsFragment == null) { // 如果ContactsFragment為空,則建立一個並新增到介面上 contactsFragment = new ContactsFragment(); transaction.add(R.id.content, contactsFragment); } else { // 如果ContactsFragment不為空,則直接將它顯示出來 transaction.show(contactsFragment); } break; case 2: // 當點選了動態tab時,改變控制元件的圖片和文字顏色 newsImage.setImageResource(R.drawable.news_selected); newsText.setTextColor(Color.WHITE); if (newsFragment == null) { // 如果NewsFragment為空,則建立一個並新增到介面上 newsFragment = new NewsFragment(); transaction.add(R.id.content, newsFragment); } else { // 如果NewsFragment不為空,則直接將它顯示出來 transaction.show(newsFragment); } break; case 3: default: // 當點選了設定tab時,改變控制元件的圖片和文字顏色 settingImage.setImageResource(R.drawable.setting_selected); settingText.setTextColor(Color.WHITE); if (settingFragment == null) { // 如果SettingFragment為空,則建立一個並新增到介面上 settingFragment = new SettingFragment(); transaction.add(R.id.content, settingFragment); } else { // 如果SettingFragment不為空,則直接將它顯示出來 transaction.show(settingFragment); } break; } transaction.commit(); } /** * 清除掉所有的選中狀態。 */ private void clearSelection() { messageImage.setImageResource(R.drawable.message_unselected); messageText.setTextColor(Color.parseColor("#82858b")); contactsImage.setImageResource(R.drawable.contacts_unselected); contactsText.setTextColor(Color.parseColor("#82858b")); newsImage.setImageResource(R.drawable.news_unselected); newsText.setTextColor(Color.parseColor("#82858b")); settingImage.setImageResource(R.drawable.setting_unselected); settingText.setTextColor(Color.parseColor("#82858b")); } /** * 將所有的Fragment都置為隱藏狀態。 * * @param transaction * 用於對Fragment執行操作的事務 */ private void hideFragments(FragmentTransaction transaction) { if (messageFragment != null) { transaction.hide(messageFragment); } if (contactsFragment != null) { transaction.hide(contactsFragment); } if (newsFragment != null) { transaction.hide(newsFragment); } if (settingFragment != null) { transaction.hide(settingFragment); } }}
這個類中的註釋已經寫得非常詳細了,下面我再帶大家簡單梳理一遍。在onCreate()方法中先是呼叫了initViews()來獲取每個控制元件的例項,並給相應的控制元件設定好點選事件,然後呼叫setTabSelection()方法設定預設的選中項,這裡傳入的0說明預設選中第1個Tab項。那麼setTabSelection()方法中又是如何處理的呢?可以看到,首先第一步是呼叫clearSelection()方法來清理掉之前的選中狀態,然後開啟一個Fragment事務,並隱藏掉所有的Fragment,以防止有多個Fragment顯示在介面上。接下來根據傳入的index引數判斷出選中的是哪一個Tab項,並改變該Tab項的圖示和文字顏色,然後將相應的Fragment新增到介面上。這裡注意一個細節,我們新增Fragment的時候並沒有使用replace()方法,而是會先判斷一下該Fragment是否為空,如果是空的則呼叫add()方法新增一個進來,如果不是空的則直接呼叫show()方法顯示出來即可。那麼為什麼沒有使用replace()方法呢?這是因為replace()方法會將被替換掉的那個Fragment徹底地移除掉,該Fragment的生命週期就結束了。當再次點選剛才那個Tab項的時候,就會讓該Fragment的生命週期重新開始,onCreate()、onCreateView()等方法都會重新執行一遍。這顯然不是我們想要的,也和ActivityGroup的工作原理不符,因此最好的解決方案就是使用hide()和show()方法來隱藏和顯示Fragment,這就不會讓Fragment的生命週期重走一遍了。
設定完預設選中項後,我們當然還可以通過點選Tab項來自由地切換介面,這就會進入到onClick()方法中。onClick()方法中的邏輯判斷非常簡單,當點選了訊息標籤時就會選中第1個tab項,點選聯絡人標籤時就會選中第2個tab項,點選動態標籤時就會選中第3個tab項,點選設定標籤時就會選中第4個tab項。都是通過呼叫setTabSelection()方法來完成的,只是傳入了不同的引數。
好了,這樣我們就將全部的程式碼都編寫完成了,下面就來執行一下吧。整個Tab的介面有點類似於QQ的感覺,並且可以通過點選不同的Tab來切換介面,如下圖所示:
另外,這個Tab介面即使在橫屏的情況下也有不錯的適用性哦,如下圖所示:
這樣,我們就成功使用Fragment編寫出了和TabHost一樣的效果。每個介面的具體邏輯就可以寫在相應的Fragment裡,效果和之前寫在Activity裡是差不多的。如此一來,我們終於可以和那個被廢棄的ActivityGroup說再見了!
好了,今天的講解到此結束,有疑問的朋友請在下面留言。
關注我的技術公眾號,每天都有優質技術文章推送。關注我的娛樂公眾號,工作、學習累了的時候放鬆一下自己。
微信掃一掃下方二維碼即可關注: