Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

用 Fragment 打造媲美 TabHost 的底部標簽導航

編輯:Android 開發實例

如今 Fragment 的應用可謂越來越廣泛。當初 Android 在 3.0 引入 Fragment,主要是為了解決平板屏幕較大、空間利用不充分的問題;而現在即便只是手機,也有越來越多的場景能發揮 Fragment 的所長。今天我們就來學一個特別實用的技巧。

很多手機應用都有這麼一個相似的功能:屏幕下方顯示一行 Tab 標簽,點擊不同標簽就能切換到不同界面。比如下面幾個應用就是典型代表。

從左到右依次是 QQ、新浪微博和支付寶錢包,可見這種底部標簽式的布局策略真的非常常見。

那這種效果該怎麼實現?熟悉 Android 的朋友一定脫口而出:用 TabHost 不就完了!殊不知 TabHost 並沒那麼簡單,它可擴展性很差,不能隨意定制 Tab 項顯示的內容,而且運行還依賴於 ActivityGroup。ActivityGroup 原本主要用於為每個 TabHost 子項管理一個單獨的 Activity,但如今已被廢棄——原因就是 Fragment 的出現!查看官方文檔對 ActivityGroup 的描述可以看到,早在 API 13 時 Android 就將其廢棄,並推薦用更靈活的 Fragment 來替代。

那剩下的問題就是:如何借助 Fragment 完成類似 TabHost 的效果?這就動手吧。

開始之前,你必須已經了解 Fragment 的用法。如果還比較陌生,建議先讀我前面的一篇文章:https://www.fengfly.com/plus/view-215089-1.html。

另外,我們還要準備好程序所需資源,比如每個 Tab 項用到的圖片。這裡我提前從 QQ 裡截了幾張圖作為項目資源,稍後會連同源碼一併給出。

新建項目 FragmentDemo,這裡我使用 4.0 的 API。

首先編寫一個類似 QQ 的主界面,當然只寫最下方的 TabHost 部分,上面的內容界面不寫——因為內容界面應該寫在 Fragment 的布局裡。打開或新建 activity_main.xml,加入如下代碼:

  1. <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" 
  2.     android:layout_width="match_parent" 
  3.     android:layout_height="match_parent" 
  4.     android:orientation="vertical" > 
  5.  
  6.     <FrameLayout 
  7.         android:id="@+id/content" 
  8.         android:layout_width="match_parent" 
  9.         android:layout_height="0dp" 
  10.         android:layout_weight="1" > 
  11.     </FrameLayout> 
  12.  
  13.     <LinearLayout 
  14.         android:layout_width="match_parent" 
  15.         android:layout_height="60dp" 
  16.         android:background="@drawable/tab_bg" > 
  17.  
  18.         <RelativeLayout 
  19.             android:id="@+id/message_layout" 
  20.             android:layout_width="0dp" 
  21.             android:layout_height="match_parent" 
  22.             android:layout_weight="1" > 
  23.  
  24.             <LinearLayout 
  25.                 android:layout_width="match_parent" 
  26.                 android:layout_height="wrap_content" 
  27.                 android:layout_centerVertical="true" 
  28.                 android:orientation="vertical" > 
  29.  
  30.                 <ImageView 
  31.                    android:id="@+id/message_image" 
  32.                     android:layout_width="wrap_content" 
  33.                     android:layout_height="wrap_content" 
  34.                     android:layout_gravity="center_horizontal" 
  35.                     android:src="@drawable/message_unselected" /> 
  36.  
  37.                 <TextView 
  38.                     android:id="@+id/message_text" 
  39.                     android:layout_width="wrap_content" 
  40.                     android:layout_height="wrap_content" 
  41.                     android:layout_gravity="center_horizontal" 
  42.                     android:text="消息" 
  43.                     android:textColor="#82858b" /> 
  44.                 </LinearLayout> 
  45.         </RelativeLayout> 
  46.  
  47.         <RelativeLayout 
  48.             android:id="@+id/contacts_layout" 
  49.             android:layout_width="0dp" 
  50.             android:layout_height="match_parent" 
  51.             android:layout_weight="1" > 
  52.  
  53.             <LinearLayout 
  54.                 android:layout_width="match_parent" 
  55.                 android:layout_height="wrap_content" 
  56.                 android:layout_centerVertical="true" 
  57.                 android:orientation="vertical" > 
  58.  
  59.                 <ImageView 
  60.                    android:id="@+id/contacts_image" 
  61.                     android:layout_width="wrap_content" 
  62.                     android:layout_height="wrap_content" 
  63.                     android:layout_gravity="center_horizontal" 
  64.                     android:src="@drawable/contacts_unselected" /> 
  65.  
  66.                 <TextView 
  67.                     android:id="@+id/contacts_text" 
  68.                     android:layout_width="wrap_content" 
  69.                     android:layout_height="wrap_content" 
  70.                     android:layout_gravity="center_horizontal" 
  71.                     android:text="聯系人" 
  72.                     android:textColor="#82858b" /> 
  73.                 </LinearLayout> 
  74.         </RelativeLayout> 
  75.  
  76.         <RelativeLayout 
  77.             android:id="@+id/news_layout" 
  78.             android:layout_width="0dp" 
  79.             android:layout_height="match_parent" 
  80.             android:layout_weight="1" > 
  81.  
  82.             <LinearLayout 
  83.                 android:layout_width="match_parent" 
  84.                 android:layout_height="wrap_content" 
  85.                 android:layout_centerVertical="true" 
  86.                 android:orientation="vertical" > 
  87.  
  88.                 <ImageView 
  89.                    android:id="@+id/news_image" 
  90.                     android:layout_width="wrap_content" 
  91.                     android:layout_height="wrap_content" 
  92.                     android:layout_gravity="center_horizontal" 
  93.                     android:src="@drawable/news_unselected" /> 
  94.  
  95.                  <TextView 
  96.                     android:id="@+id/news_text" 
  97.                     android:layout_width="wrap_content" 
  98.                     android:layout_height="wrap_content" 
  99.                     android:layout_gravity="center_horizontal" 
  100.                     android:text="動態" 
  101.                     android:textColor="#82858b" /> 
  102.                 </LinearLayout> 
  103.         </RelativeLayout> 
  104.  
  105.         <RelativeLayout 
  106.             android:id="@+id/setting_layout" 
  107.             android:layout_width="0dp" 
  108.             android:layout_height="match_parent" 
  109.             android:layout_weight="1" > 
  110.  
  111.             <LinearLayout 
  112.                 android:layout_width="match_parent" 
  113.                 android:layout_height="wrap_content" 
  114.                 android:layout_centerVertical="true" 
  115.                 android:orientation="vertical" > 
  116.  
  117.                 <ImageView 
  118.                    android:id="@+id/setting_image" 
  119.                     android:layout_width="wrap_content" 
  120.                     android:layout_height="wrap_content" 
  121.                     android:layout_gravity="center_horizontal" 
  122.                     android:src="@drawable/setting_unselected" /> 
  123.  
  124.                 <TextView 
  125.                     android:id="@+id/setting_text" 
  126.                     android:layout_width="wrap_content" 
  127.                     android:layout_height="wrap_content" 
  128.                     android:layout_gravity="center_horizontal" 
  129.                     android:text="設置" 
  130.                     android:textColor="#82858b" /> 
  131.                 </LinearLayout> 
  132.         </RelativeLayout> 
  133.     </LinearLayout> 
  134.  
  135. </LinearLayout> 

這段布局雖長,其實主要分兩部分。第一部分是 FrameLayout,這裡只把它的 id 設為 content,不添加任何具體內容,因為內容要在後面動態加進來。第二部分是它下面的 LinearLayout,也就是整個類似 TabHost 的布局。可以看到,這個 LinearLayout 又被等分成四份,每份顯示一個 ImageView 和一個 TextView:ImageView 顯示 Tab 圖標,TextView 顯示 Tab 標題,效果便和 QQ 非常接近。

既然等分了四份,接下來自然要分別實現四個 Fragment 及其布局。新建 message_layout.xml 作為消息界面布局:

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" 
  3.     android:layout_width="match_parent" 
  4.     android:layout_height="match_parent" > 
  5.  
  6.     <LinearLayout 
  7.         android:layout_width="wrap_content" 
  8.         android:layout_height="wrap_content" 
  9.         android:layout_centerInParent="true" 
  10.         android:orientation="vertical" > 
  11.  
  12.         <ImageView 
  13.             android:layout_width="wrap_content" 
  14.             android:layout_height="wrap_content" 
  15.             android:layout_gravity="center_horizontal" 
  16.             android:src="@drawable/message_selected" /> 
  17.  
  18.         <TextView 
  19.             android:layout_width="wrap_content" 
  20.             android:layout_height="wrap_content" 
  21.             android:layout_gravity="center_horizontal" 
  22.             android:padding="10dp" 
  23.             android:text="這是消息界面" 
  24.             android:textSize="20sp" /> 
  25.     </LinearLayout> 
  26.  
  27. </RelativeLayout> 

這個布局就簡單多了,只是在屏幕正中央顯示一個消息圖標和一段文字。接著創建對應的 Fragment,新建 MessageFragment 繼承自 Fragment:

  1. public class MessageFragment extends Fragment {  
  2.  
  3.     public View onCreateView(LayoutInflater inflater, ViewGroup container, 
  4.             Bundle savedInstanceState) {  
  5.         View messageLayout = inflater.inflate(R.layout.message_layout, container, false);  
  6.         return messageLayout;  
  7.     }  
  8.  
  9. }  

後面就依葫蘆畫瓢,把其餘幾個 Fragment 及布局一一創建出來。新建 contacts_layout.xml 作為聯系人界面布局:

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" 
  3.     android:layout_width="match_parent" 
  4.     android:layout_height="match_parent" > 
  5.  
  6.     <LinearLayout 
  7.         android:layout_width="wrap_content" 
  8.         android:layout_height="wrap_content" 
  9.         android:layout_centerInParent="true" 
  10.         android:orientation="vertical" > 
  11.  
  12.         <ImageView 
  13.             android:layout_width="wrap_content" 
  14.             android:layout_height="wrap_content" 
  15.             android:layout_gravity="center_horizontal" 
  16.             android:src="@drawable/contacts_selected" /> 
  17.  
  18.         <TextView 
  19.             android:layout_width="wrap_content" 
  20.             android:layout_height="wrap_content" 
  21.             android:layout_gravity="center_horizontal" 
  22.             android:padding="10dp" 
  23.             android:text="這是聯系人界面" 
  24.             android:textSize="20sp" /> 
  25.     </LinearLayout> 
  26.  
  27. </RelativeLayout> 

再新建 ContactsFragment 繼承自 Fragment:

  1. public class ContactsFragment extends Fragment {  
  2.  
  3.     @Override 
  4.     public View onCreateView(LayoutInflater inflater, ViewGroup container, 
  5.             Bundle savedInstanceState) {  
  6.         View contactsLayout = inflater.inflate(R.layout.contacts_layout, 
  7.                 container, false);  
  8.         return contactsLayout;  
  9.     }  
  10.  
  11. }  

然後新建 news_layout.xml 作為動態界面布局:

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" 
  3.     android:layout_width="match_parent" 
  4.     android:layout_height="match_parent" > 
  5.  
  6.     <LinearLayout 
  7.         android:layout_width="wrap_content" 
  8.         android:layout_height="wrap_content" 
  9.         android:layout_centerInParent="true" 
  10.         android:orientation="vertical" > 
  11.  
  12.         <ImageView 
  13.             android:layout_width="wrap_content" 
  14.             android:layout_height="wrap_content" 
  15.             android:layout_gravity="center_horizontal" 
  16.             android:src="@drawable/news_selected" /> 
  17.  
  18.         <TextView 
  19.             android:layout_width="wrap_content" 
  20.             android:layout_height="wrap_content" 
  21.             android:layout_gravity="center_horizontal" 
  22.             android:padding="10dp" 
  23.             android:text="這是動態界面" 
  24.             android:textSize="20sp" /> 
  25.     </LinearLayout> 
  26.  
  27. </RelativeLayout> 

再新建 NewsFragment 繼承自 Fragment:

  1. public class NewsFragment extends Fragment {  
  2.  
  3.     @Override 
  4.     public View onCreateView(LayoutInflater inflater, ViewGroup container, 
  5.             Bundle savedInstanceState) {  
  6.         View newsLayout = inflater.inflate(R.layout.news_layout, container, 
  7.                 false);  
  8.         return newsLayout;  
  9.     }  
  10.  
  11. }  

最後新建 setting_layout.xml 作為設置界面布局:

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" 
  3.     android:layout_width="match_parent" 
  4.     android:layout_height="match_parent" > 
  5.  
  6.     <LinearLayout 
  7.         android:layout_width="wrap_content" 
  8.         android:layout_height="wrap_content" 
  9.         android:layout_centerInParent="true" 
  10.         android:orientation="vertical" > 
  11.  
  12.         <ImageView 
  13.             android:layout_width="wrap_content" 
  14.             android:layout_height="wrap_content" 
  15.             android:layout_gravity="center_horizontal" 
  16.             android:src="@drawable/setting_selected" /> 
  17.  
  18.         <TextView 
  19.             android:layout_width="wrap_content" 
  20.             android:layout_height="wrap_content" 
  21.             android:layout_gravity="center_horizontal" 
  22.             android:padding="10dp" 
  23.             android:text="這是設置界面" 
  24.             android:textSize="20sp" /> 
  25.     </LinearLayout> 
  26.  
  27. </RelativeLayout> 

再新建 SettingFragment 繼承自 Fragment:

  1. public class SettingFragment extends Fragment {  
  2.  
  3.     @Override 
  4.     public View onCreateView(LayoutInflater inflater, ViewGroup container, 
  5.             Bundle savedInstanceState) {  
  6.         View settingLayout = inflater.inflate(R.layout.setting_layout, 
  7.                 container, false);  
  8.         return settingLayout;  
  9.     }  
  10.  
  11. }  

這樣,四個 Fragment 及其布局就都建好了。接下來是最關鍵的一步——打開或新建 MainActivity 作為主 Activity:

  1. /**  
  2.  * 項目的主Activity,所有的Fragment都嵌入在這裡。  
  3.  *   
  4.  * @author guolin  
  5.  */ 
  6. public class MainActivity extends Activity implements OnClickListener {  
  7.  
  8.     /**  
  9.      * 用於展示消息的Fragment  
  10.      */ 
  11.     private MessageFragment messageFragment;  
  12.  
  13.     /**  
  14.      * 用於展示聯系人的Fragment  
  15.      */ 
  16.     private ContactsFragment contactsFragment;  
  17.  
  18.     /**  
  19.      * 用於展示動態的Fragment  
  20.      */ 
  21.     private NewsFragment newsFragment;  
  22.  
  23.     /**  
  24.      * 用於展示設置的Fragment  
  25.      */ 
  26.     private SettingFragment settingFragment;  
  27.  
  28.     /**  
  29.      * 消息界面布局  
  30.      */ 
  31.     private View messageLayout;  
  32.  
  33.     /**  
  34.      * 聯系人界面布局  
  35.      */ 
  36.     private View contactsLayout;  
  37.  
  38.     /**  
  39.      * 動態界面布局  
  40.      */ 
  41.     private View newsLayout;  
  42.  
  43.     /**  
  44.      * 設置界面布局  
  45.      */ 
  46.     private View settingLayout;  
  47.  
  48.     /**  
  49.      * 在Tab布局上顯示消息圖標的控件  
  50.      */ 
  51.     private ImageView messageImage;  
  52.  
  53.     /**  
  54.      * 在Tab布局上顯示聯系人圖標的控件  
  55.      */ 
  56.     private ImageView contactsImage;  
  57.  
  58.     /**  
  59.      * 在Tab布局上顯示動態圖標的控件  
  60.      */ 
  61.     private ImageView newsImage;  
  62.  
  63.     /**  
  64.      * 在Tab布局上顯示設置圖標的控件  
  65.      */ 
  66.     private ImageView settingImage;  
  67.  
  68.     /**  
  69.      * 在Tab布局上顯示消息標題的控件  
  70.      */ 
  71.     private TextView messageText;  
  72.  
  73.     /**  
  74.      * 在Tab布局上顯示聯系人標題的控件  
  75.      */ 
  76.     private TextView contactsText;  
  77.  
  78.     /**  
  79.      * 在Tab布局上顯示動態標題的控件  
  80.      */ 
  81.     private TextView newsText;  
  82.  
  83.     /**  
  84.      * 在Tab布局上顯示設置標題的控件  
  85.      */ 
  86.     private TextView settingText;  
  87.  
  88.     /**  
  89.      * 用於對Fragment進行管理  
  90.      */ 
  91.     private FragmentManager fragmentManager;  
  92.  
  93.     @Override 
  94.     protected void onCreate(Bundle savedInstanceState) {  
  95.         super.onCreate(savedInstanceState);  
  96.         requestWindowFeature(Window.FEATURE_NO_TITLE);  
  97.         setContentView(R.layout.activity_main);  
  98.         // 初始化布局元素  
  99.         initViews();  
  100.         fragmentManager = getFragmentManager();  
  101.         // 第一次啟動時選中第0個tab  
  102.         setTabSelection(0);  
  103.     }  
  104.  
  105.     /**  
  106.      * 在這裡獲取到每個需要用到的控件的實例,並給它們設置好必要的點擊事件。  
  107.      */ 
  108.     private void initViews() {  
  109.         messageLayout = findViewById(R.id.message_layout);  
  110.         contactsLayout = findViewById(R.id.contacts_layout);  
  111.         newsLayout = findViewById(R.id.news_layout);  
  112.         settingLayout = findViewById(R.id.setting_layout);  
  113.         messageImage = (ImageView) findViewById(R.id.message_image);  
  114.         contactsImage = (ImageView) findViewById(R.id.contacts_image);  
  115.         newsImage = (ImageView) findViewById(R.id.news_image);  
  116.         settingImage = (ImageView) findViewById(R.id.setting_image);  
  117.         messageText = (TextView) findViewById(R.id.message_text);  
  118.         contactsText = (TextView) findViewById(R.id.contacts_text);  
  119.         newsText = (TextView) findViewById(R.id.news_text);  
  120.         settingText = (TextView) findViewById(R.id.setting_text);  
  121.         messageLayout.setOnClickListener(this);  
  122.         contactsLayout.setOnClickListener(this);  
  123.         newsLayout.setOnClickListener(this);  
  124.         settingLayout.setOnClickListener(this);  
  125.     }  
  126.  
  127.     @Override 
  128.     public void onClick(View v) {  
  129.         switch (v.getId()) {  
  130.         case R.id.message_layout: 
  131.             // 當點擊了消息tab時,選中第1個tab  
  132.             setTabSelection(0);  
  133.             break;  
  134.         case R.id.contacts_layout: 
  135.             // 當點擊了聯系人tab時,選中第2個tab  
  136.             setTabSelection(1);  
  137.             break;  
  138.         case R.id.news_layout: 
  139.             // 當點擊了動態tab時,選中第3個tab  
  140.             setTabSelection(2);  
  141.             break;  
  142.         case R.id.setting_layout: 
  143.             // 當點擊了設置tab時,選中第4個tab  
  144.             setTabSelection(3);  
  145.             break;  
  146.         default: 
  147.             break;  
  148.         }  
  149.     }  
  150.  
  151.     /**  
  152.      * 根據傳入的index參數來設置選中的tab頁。  
  153.      *   
  154.      * @param index  
  155.      *            每個tab頁對應的下標。0表示消息,1表示聯系人,2表示動態,3表示設置。  
  156.      */ 
  157.     private void setTabSelection(int index) {  
  158.         // 每次選中之前先清楚掉上次的選中狀態  
  159.         clearSelection();  
  160.         // 開啟一個Fragment事務  
  161.         FragmentTransaction transaction = fragmentManager.beginTransaction();  
  162.         // 先隱藏掉所有的Fragment,以防止有多個Fragment顯示在界面上的情況  
  163.         hideFragments(transaction);  
  164.         switch (index) {  
  165.         case 0: 
  166.             // 當點擊了消息tab時,改變控件的圖片和文字顏色  
  167.             messageImage.setImageResource(R.drawable.message_selected);  
  168.             messageText.setTextColor(Color.WHITE);  
  169.             if (messageFragment == null) {  
  170.                 // 如果MessageFragment為空,則創建一個並添加到界面上  
  171.                 messageFragment = new MessageFragment();  
  172.                 transaction.add(R.id.content, messageFragment);  
  173.             }else {  
  174.                 // 如果MessageFragment不為空,則直接將它顯示出來  
  175.                 transaction.show(messageFragment);  
  176.             }  
  177.             break;  
  178.         case 1: 
  179.             // 當點擊了聯系人tab時,改變控件的圖片和文字顏色  
  180.             contactsImage.setImageResource(R.drawable.contacts_selected);  
  181.             contactsText.setTextColor(Color.WHITE);  
  182.             if (contactsFragment == null) {  
  183.                 // 如果ContactsFragment為空,則創建一個並添加到界面上  
  184.                 contactsFragment = new ContactsFragment();  
  185.                 transaction.add(R.id.content, contactsFragment);  
  186.             }else {  
  187.                 // 如果ContactsFragment不為空,則直接將它顯示出來  
  188.                 transaction.show(contactsFragment);  
  189.             }  
  190.             break;  
  191.         case 2: 
  192.             // 當點擊了動態tab時,改變控件的圖片和文字顏色  
  193.             newsImage.setImageResource(R.drawable.news_selected);  
  194.             newsText.setTextColor(Color.WHITE);  
  195.             if (newsFragment == null) {  
  196.                 // 如果NewsFragment為空,則創建一個並添加到界面上  
  197.                 newsFragment = new NewsFragment();  
  198.                 transaction.add(R.id.content, newsFragment);  
  199.             }else {  
  200.                 // 如果NewsFragment不為空,則直接將它顯示出來  
  201.                 transaction.show(newsFragment);  
  202.             }  
  203.             break;  
  204.         case 3: 
  205.         default: 
  206.             // 當點擊了設置tab時,改變控件的圖片和文字顏色  
  207.             settingImage.setImageResource(R.drawable.setting_selected);  
  208.             settingText.setTextColor(Color.WHITE);  
  209.             if (settingFragment == null) {  
  210.                 // 如果SettingFragment為空,則創建一個並添加到界面上  
  211.                 settingFragment = new SettingFragment();  
  212.                 transaction.add(R.id.content, settingFragment);  
  213.             }else {  
  214.                 // 如果SettingFragment不為空,則直接將它顯示出來  
  215.                 transaction.show(settingFragment);  
  216.             }  
  217.             break;  
  218.         }  
  219.         transaction.commit();  
  220.     }  
  221.  
  222.     /**  
  223.      * 清除掉所有的選中狀態。  
  224.      */ 
  225.     private void clearSelection() {  
  226.         messageImage.setImageResource(R.drawable.message_unselected);  
  227.         messageText.setTextColor(Color.parseColor("#82858b"));  
  228.         contactsImage.setImageResource(R.drawable.contacts_unselected);  
  229.         contactsText.setTextColor(Color.parseColor("#82858b"));  
  230.         newsImage.setImageResource(R.drawable.news_unselected);  
  231.         newsText.setTextColor(Color.parseColor("#82858b"));  
  232.         settingImage.setImageResource(R.drawable.setting_unselected);  
  233.         settingText.setTextColor(Color.parseColor("#82858b"));  
  234.     }  
  235.  
  236.     /**  
  237.      * 將所有的Fragment都置為隱藏狀態。  
  238.      *   
  239.      * @param transaction  
  240.      *            用於對Fragment執行操作的事務  
  241.      */ 
  242.     private void hideFragments(FragmentTransaction transaction) {  
  243.         if (messageFragment != null) {  
  244.             transaction.hide(messageFragment);  
  245.         }  
  246.         if (contactsFragment != null) {  
  247.             transaction.hide(contactsFragment);  
  248.         }  
  249.         if (newsFragment != null) {  
  250.             transaction.hide(newsFragment);  
  251.         }  
  252.         if (settingFragment != null) {  
  253.             transaction.hide(settingFragment);  
  254.         }  
  255.     }  
  256. }  

這個類的註釋已經寫得很詳細,我再幫大家快速梳理一遍。onCreate() 中先調用 initViews() 拿到每個控件的實例並設好點擊事件,再調用 setTabSelection() 設置默認選中項,傳入的 0 表示默認選中第 1 個 Tab。

setTabSelection() 又是如何處理的呢?第一步先調用 clearSelection() 清理上次的選中狀態,接著開啟一個 Fragment 事務並隱藏所有 Fragment,避免多個 Fragment 同時顯示。然後根據傳入的 index 判斷選中的是哪個 Tab,改變該 Tab 的圖標和文字顏色,再把相應的 Fragment 添加到界面上。這裡有個細節:添加 Fragment 時並沒有使用 replace(),而是先判斷該 Fragment 是否為空——為空則用 add() 添加,不為空則直接用 show() 顯示。為什麼不用 replace()?因為 replace() 會把被替換的 Fragment 徹底移除,其生命週期就此結束;再次點擊時又會重新走一遍 onCreate()、onCreateView() 等,這顯然不是我們想要的,也不符合 ActivityGroup 的行為。所以最好的方案是用 hide() 和 show() 來隱藏與顯示,這樣 Fragment 的生命週期就不會重走一遭。

設置好默認項後,我們還能通過點擊 Tab 自由切換界面,這便進入 onClick()。它的邏輯很簡單:點消息選第 1 個、點聯系人選第 2 個、點動態選第 3 個、點設置選第 4 個,都是調用 setTabSelection() 只是傳入不同參數。

全部代碼編寫完成,運行起來看看吧。整個 Tab 界面頗有幾分 QQ 的感覺,點擊不同 Tab 即可切換界面;即使在橫屏下也有不錯的適配性。

就這樣,我們成功用 Fragment 編寫出了和 TabHost 一樣的效果。每個界面的具體邏輯都可以寫在各自的 Fragment 裡,效果與寫在 Activity 中相差無幾。如此一來,我們終於可以和被廢棄的 ActivityGroup 說再見了!

源碼下載,請點擊這裡。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved