Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 底部標籤切換 Fragment 的完整實作

編輯:關於 Android 程式設計

底部 Tab 互換是 App 最常見的骨架,微信就是典型例子。本篇先聚焦最基礎的版本:點擊底部標籤切換 Fragment(不含左右滑動)。

效果預覽:


 

整個畫面可以拆成三塊:
第一部分:頂部標題欄
第二部分:中部內容區(放 Fragment)
第三部分:底部標籤欄

 /BottomTabDemo/res/layout/activity_main.xml

 <FrameLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <RelativeLayout android:id="@+id/rl_main" android:layout_width="match_parent" android:layout_height="match_parent" > <!-- 頂部 --> <RelativeLayout android:id="@+id/top_tab" android:layout_width="match_parent" android:layout_height="50dip" android:background="@color/topbar_bg" > <ImageView android:id="@+id/iv_logo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:focusable="false" android:src="@drawable/zhidao_logo" android:contentDescription="@null" /> </RelativeLayout> <!-- 底部tab --> <LinearLayout android:id="@+id/ll_bottom_tab" android:layout_width="match_parent" android:layout_height="54dp" android:layout_alignParentBottom="true" android:gravity="center_vertical" android:orientation="horizontal" android:baselineAligned="true"> <RelativeLayout android:id="@+id/rl_know" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1.0" > <ImageView android:id="@+id/iv_know" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:src="@drawable/btn_know_nor" android:contentDescription="@null"/> <TextView android:id="@+id/tv_know" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/iv_know" android:layout_centerHorizontal="true" android:text="@string/bottom_tab_know" android:textColor="@color/bottomtab_normal" android:textSize="12sp" /> </RelativeLayout> <RelativeLayout android:id="@+id/rl_want_know" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1.0" > <ImageView android:id="@+id/iv_i_want_know" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:src="@drawable/btn_wantknow_nor" android:contentDescription="@null" /> <TextView android:id="@+id/tv_i_want_know" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/iv_i_want_know" android:layout_centerHorizontal="true" android:text="@string/bottom_tab_wantknow" android:textColor="@color/bottomtab_normal" android:textSize="12sp" /> </RelativeLayout> <RelativeLayout android:id="@+id/rl_me" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1.0" > <ImageView android:id="@+id/iv_me" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:src="@drawable/btn_my_nor" android:contentDescription="@null" /> <TextView android:id="@+id/tv_me" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/iv_me" android:layout_centerHorizontal="true" android:text="@string/bottom_tab_my" android:textColor="@color/bottomtab_normal" android:textSize="12sp" /> </RelativeLayout> </LinearLayout> <!-- 內容部分, fragment切換 --> <LinearLayout android:id="@+id/content_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_above="@+id/line" android:layout_below="@+id/top_tab" android:orientation="vertical" > </LinearLayout> <View android:id="@+id/line" android:layout_width="match_parent" android:layout_height="1dp" android:layout_above="@id/ll_bottom_tab" android:background="@color/line" /> </RelativeLayout> </FrameLayout> 

版面配置有幾個細節:底部三個 Tab 都用 layout_width="0dp" 搭配 layout_weight="1.0" 做等分,內容區用 layout_above 與 layout_below 夾在標題欄與分隔線之間,這樣不管標題欄或底部高度怎麼變,內容區都會自動跟著伸縮。

接下來要處理的是「切換時改變標籤狀態」,主要有兩件事:

  • 切換圖示(未選中/已選中兩套資源)
  • 切換文字顏色

同時內容區要換成不同的 Fragment,這裡定義三個:
/BottomTabDemo/src/com/xiaowu/bottomtab/demo/ZhidaoFragment.java
/BottomTabDemo/src/com/xiaowu/bottomtab/demo/IWantKnowFragment.java
/BottomTabDemo/src/com/xiaowu/bottomtab/demo/MeFragment.java

各自對應一個版面檔:
/BottomTabDemo/res/layout/main_tab1_fragment.xml
/BottomTabDemo/res/layout/main_tab2_fragment.xml
/BottomTabDemo/res/layout/main_tab3_fragment.xml

Fragment 切換的核心方法是這個:

 /** * 添加或者顯示碎片 * * @param transaction * @param fragment */ private void addOrShowFragment(FragmentTransaction transaction, Fragment fragment) { if (currentFragment == fragment) return; if (!fragment.isAdded()) { // 如果當前fragment未被添加,則添加到Fragment管理器中 transaction.hide(currentFragment) .add(R.id.content_layout, fragment).commit(); } else { transaction.hide(currentFragment).show(fragment).commit(); } currentFragment = fragment; } 

這個 hide/show 策略是重點。若改用 replace(),每次切 Tab 都會銷毀並重建 Fragment,使用者在列表頁滾到一半切去別頁再切回來,位置就飛了。hide/show 則是保留實例只切可見性,狀態完整保住,代價是記憶體佔用較高。對 Tab 這種「使用者會反覆切換」的場景,這個取捨通常是對的。

完整程式碼:

/BottomTabDemo/src/com/xiaowu/bottomtab/demo/MainActivity.java 

 package com.xiaowu.bottomtab.demo; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentTransaction; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; /** * 主Activity * * @author wwj_748 * */ public class MainActivity extends FragmentActivity implements OnClickListener { // 三個tab布局 private RelativeLayout knowLayout, iWantKnowLayout, meLayout; // 底部標簽切換的Fragment private Fragment knowFragment, iWantKnowFragment, meFragment, currentFragment; // 底部標簽圖片 private ImageView knowImg, iWantKnowImg, meImg; // 底部標簽的文本 private TextView knowTv, iWantKnowTv, meTv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initUI(); initTab(); } /** * 初始化UI */ private void initUI() { knowLayout = (RelativeLayout) findViewById(R.id.rl_know); iWantKnowLayout = (RelativeLayout) findViewById(R.id.rl_want_know); meLayout = (RelativeLayout) findViewById(R.id.rl_me); knowLayout.setOnClickListener(this); iWantKnowLayout.setOnClickListener(this); meLayout.setOnClickListener(this); knowImg = (ImageView) findViewById(R.id.iv_know); iWantKnowImg = (ImageView) findViewById(R.id.iv_i_want_know); meImg = (ImageView) findViewById(R.id.iv_me); knowTv = (TextView) findViewById(R.id.tv_know); iWantKnowTv = (TextView) findViewById(R.id.tv_i_want_know); meTv = (TextView) findViewById(R.id.tv_me); } /** * 初始化底部標簽 */ private void initTab() { if (knowFragment == null) { knowFragment = new ZhidaoFragment(); } if (!knowFragment.isAdded()) { // 提交事務 getSupportFragmentManager().beginTransaction() .add(R.id.content_layout, knowFragment).commit(); // 記錄當前Fragment currentFragment = knowFragment; // 設置圖片文本的變化 knowImg.setImageResource(R.drawable.btn_know_pre); knowTv.setTextColor(getResources() .getColor(R.color.bottomtab_press)); iWantKnowImg.setImageResource(R.drawable.btn_wantknow_nor); iWantKnowTv.setTextColor(getResources().getColor( R.color.bottomtab_normal)); meImg.setImageResource(R.drawable.btn_my_nor); meTv.setTextColor(getResources().getColor(R.color.bottomtab_normal)); } } @Override public void onClick(View view) { switch (view.getId()) { case R.id.rl_know: // 知道 clickTab1Layout(); break; case R.id.rl_want_know: // 我想知道 clickTab2Layout(); break; case R.id.rl_me: // 我的 clickTab3Layout(); break; default: break; } } /** * 點擊第一個tab */ private void clickTab1Layout() { if (knowFragment == null) { knowFragment = new ZhidaoFragment(); } addOrShowFragment(getSupportFragmentManager().beginTransaction(), knowFragment); // 設置底部tab變化 knowImg.setImageResource(R.drawable.btn_know_pre); knowTv.setTextColor(getResources().getColor(R.color.bottomtab_press)); iWantKnowImg.setImageResource(R.drawable.btn_wantknow_nor); iWantKnowTv.setTextColor(getResources().getColor( R.color.bottomtab_normal)); meImg.setImageResource(R.drawable.btn_my_nor); meTv.setTextColor(getResources().getColor(R.color.bottomtab_normal)); } /** * 點擊第二個tab */ private void clickTab2Layout() { if (iWantKnowFragment == null) { iWantKnowFragment = new IWantKnowFragment(); } addOrShowFragment(getSupportFragmentManager().beginTransaction(), iWantKnowFragment); knowImg.setImageResource(R.drawable.btn_know_nor); knowTv.setTextColor(getResources().getColor(R.color.bottomtab_normal)); iWantKnowImg.setImageResource(R.drawable.btn_wantknow_pre); iWantKnowTv.setTextColor(getResources().getColor( R.color.bottomtab_press)); meImg.setImageResource(R.drawable.btn_my_nor); meTv.setTextColor(getResources().getColor(R.color.bottomtab_normal)); } /** * 點擊第三個tab */ private void clickTab3Layout() { if (meFragment == null) { meFragment = new MeFragment(); } addOrShowFragment(getSupportFragmentManager().beginTransaction(), meFragment); knowImg.setImageResource(R.drawable.btn_know_nor); knowTv.setTextColor(getResources().getColor(R.color.bottomtab_normal)); iWantKnowImg.setImageResource(R.drawable.btn_wantknow_nor); iWantKnowTv.setTextColor(getResources().getColor( R.color.bottomtab_normal)); meImg.setImageResource(R.drawable.btn_my_pre); meTv.setTextColor(getResources().getColor(R.color.bottomtab_press)); } /** * 添加或者顯示碎片 * * @param transaction * @param fragment */ private void addOrShowFragment(FragmentTransaction transaction, Fragment fragment) { if (currentFragment == fragment) return; if (!fragment.isAdded()) { // 如果當前fragment未被添加,則添加到Fragment管理器中 transaction.hide(currentFragment) .add(R.id.content_layout, fragment).commit(); } else { transaction.hide(currentFragment).show(fragment).commit(); } currentFragment = fragment; } } 

幾處可以寫得更好的地方

重複程式碼太多。三個 clickTabNLayout() 除了 Fragment 與資源 id 不同,其餘幾乎一模一樣。應該抽成一個方法,並用陣列或枚舉管理 Tab 的狀態:

把 Tab 的圖示、文字顏色、Fragment 類別各自放進陣列,再寫一個 selectTab(int index) 迴圈更新全部 Tab 的樣式、只切換 Fragment。這樣新增第四個 Tab 只需加一筆資料,不必複製第三個方法。

hide(currentFragment) 的隱藏危機。第一次呼叫 addOrShowFragment() 時 currentFragment 已被 initTab() 設為 knowFragment,所以不會出問題;但若日後調整初始化順序,hide(null) 會直接拋 NPE。加一行 null 檢查更保險。

getColor 的版本問題。getResources().getColor(int) 在 API 23 已標記為 deprecated,建議改用 ContextCompat.getColor(this, R.color.xxx) 或 getResources().getColor(id, theme)。

可以用 FragmentContainerView。現行寫法用一個空 LinearLayout 當容器,改成 FragmentContainerView 或直接宣告 <fragment> 標籤會更直觀,也能少寫一部分事務程式碼。

以上就是底部 Tab 切換 Fragment 的完整實作,核心觀念只有兩個:用 hide/show 保留狀態,以及每次切換都同步更新所有 Tab 的視覺樣式。

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