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

Fragment 實作底部導航欄:從佈局到切換邏輯的完整教學

編輯:關於 Android 程式設計

上一節回顧了 Fragment 的基本概念,這次直接進到實戰:用 Fragment 做一個簡陋但完整的底部導航欄。

先看成品的樣子:

視覺上不複雜,實作起來確實也不難。先把流程想清楚,再動手寫程式。

實現流程

整體思路是:主佈局上方放一個 FrameLayout 作為 Fragment 容器,下方放一條包含三個 Item 的 LinearLayout 作為導航列;點擊某個 Item 時,隱藏其餘 Fragment 並顯示對應的那一個,同時切換圖示與文字顏色。

Step 1:寫主佈局

每個導航項都是「上圖下文」的結構,寫好一份之後複製兩份、替換圖片與文字即可:

<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/ic_tabbar_settings_normal" />

        <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="#7597B3" />
    </LinearLayout>
</RelativeLayout>

完整的 activity_main.xml:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <!-- Fragment 容器 -->
    <FrameLayout
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <!-- 底部導航欄 -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:background="#FFFFFF"
        android:orientation="horizontal" >

        <RelativeLayout
            android:id="@+id/course_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/course_image"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal"
                    android:src="@drawable/ic_tabbar_course_normal" />
                <TextView
                    android:id="@+id/course_text"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal"
                    android:text="日程"
                    android:textColor="#7597B3" />
            </LinearLayout>
        </RelativeLayout>

        <!-- found_layout 與 setting_layout 結構相同,替換 id、圖片與文字 -->
        ...
    </LinearLayout>
</LinearLayout>

這裡有兩個細節值得注意:FrameLayout 的高度寫成 0dp 搭配 layout_weight="1",才能自動吃掉扣除導航列後的所有剩餘空間;三個導航項都用 layout_width="0dp" 加權重平均分配,避免不同解析度下寬度不一致。

Step 2:寫三個 Fragment 的佈局

這部分看需求,本例只放一個 TextView 作為佔位,方便辨識目前顯示的是哪一頁:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FAECD8"
    android:gravity="center"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="日程表 Fragment" />
</LinearLayout>

一式三份,各自改掉背景色與文字即可。

Step 3:寫三個 Fragment 實作類

public class Fragment1 extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fg1, container, false);
    }
}

同樣複製三份,只替換 inflate() 載入的佈局資源。

Step 4:MainActivity 的切換邏輯

public class MainActivity extends FragmentActivity implements OnClickListener {

    // 三個 Fragment 物件
    private Fragment1 fg1;
    private Fragment2 fg2;
    private Fragment3 fg3;

    // Fragment 容器
    private FrameLayout flayout;

    // 底部導航欄的三個項
    private RelativeLayout course_layout, found_layout, settings_layout;

    // 導航欄中的圖示與文字
    private ImageView course_image, found_image, settings_image;
    private TextView course_text, found_text, settings_text;

    // 顏色值
    private final int white = 0xFFFFFFFF;
    private final int gray  = 0xFF7597B3;
    private final int blue  = 0xFF0AB2FB;

    private FragmentManager fManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fManager = getSupportFragmentManager();
        initViews();
    }

    /** 完成元件初始化 */
    public void initViews() {
        course_image   = (ImageView) findViewById(R.id.course_image);
        found_image    = (ImageView) findViewById(R.id.found_image);
        settings_image = (ImageView) findViewById(R.id.setting_image);
        course_text    = (TextView) findViewById(R.id.course_text);
        found_text     = (TextView) findViewById(R.id.found_text);
        settings_text  = (TextView) findViewById(R.id.setting_text);

        course_layout   = (RelativeLayout) findViewById(R.id.course_layout);
        found_layout    = (RelativeLayout) findViewById(R.id.found_layout);
        settings_layout = (RelativeLayout) findViewById(R.id.setting_layout);

        course_layout.setOnClickListener(this);
        found_layout.setOnClickListener(this);
        settings_layout.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.course_layout:
                setChioceItem(0);
                break;
            case R.id.found_layout:
                setChioceItem(1);
                break;
            case R.id.setting_layout:
                setChioceItem(2);
                break;
            default:
                break;
        }
    }

    /** 選中某個項目後的處理 */
    public void setChioceItem(int index) {
        // 先重置樣式,再把所有 Fragment 隱藏起來
        FragmentTransaction transaction = fManager.beginTransaction();
        clearChioce();
        hideFragments(transaction);

        switch (index) {
            case 0:
                course_image.setImageResource(R.drawable.ic_tabbar_course_pressed);
                course_text.setTextColor(blue);
                course_layout.setBackgroundResource(R.drawable.ic_tabbar_bg_click);
                if (fg1 == null) {
                    fg1 = new Fragment1();
                    transaction.add(R.id.content, fg1);
                } else {
                    transaction.show(fg1);
                }
                break;
            case 1:
                found_image.setImageResource(R.drawable.ic_tabbar_found_pressed);
                found_text.setTextColor(blue);
                found_layout.setBackgroundResource(R.drawable.ic_tabbar_bg_click);
                if (fg2 == null) {
                    fg2 = new Fragment2();
                    transaction.add(R.id.content, fg2);
                } else {
                    transaction.show(fg2);
                }
                break;
            case 2:
                settings_image.setImageResource(R.drawable.ic_tabbar_settings_pressed);
                settings_text.setTextColor(blue);
                settings_layout.setBackgroundResource(R.drawable.ic_tabbar_bg_click);
                if (fg3 == null) {
                    fg3 = new Fragment3();
                    transaction.add(R.id.content, fg3);
                } else {
                    transaction.show(fg3);
                }
                break;
            default:
                break;
        }
        transaction.commit();
    }

    /** 隱藏所有 Fragment,避免顯示狀態混亂 */
    private void hideFragments(FragmentTransaction transaction) {
        if (fg1 != null) transaction.hide(fg1);
        if (fg2 != null) transaction.hide(fg2);
        if (fg3 != null) transaction.hide(fg3);
    }

    /** 重置所有項目的樣式 */
    public void clearChioce() {
        course_image.setImageResource(R.drawable.ic_tabbar_course_normal);
        course_layout.setBackgroundColor(white);
        course_text.setTextColor(gray);

        found_image.setImageResource(R.drawable.ic_tabbar_found_normal);
        found_layout.setBackgroundColor(white);
        found_text.setTextColor(gray);

        settings_image.setImageResource(R.drawable.ic_tabbar_settings_normal);
        settings_layout.setBackgroundColor(white);
        settings_text.setTextColor(gray);
    }
}

為什麼用 hide/show 而不是 replace?

這是這個模式最常被問到的問題。replace() 會銷毀目前 Fragment 的 View 並重建新的,每次切換都要重新 inflate、重新載入資料,代價不小;hide()/show() 只是切換可見性,View 一直留在記憶體裡,切換幾乎零成本。代價是佔用較多記憶體,但對只有三、四個頁籤的底部導航而言,這個取捨非常划算。

幾個容易踩到的細節

  • v4 套件與 app 套件不要混用。這是最常見的錯誤。若專案minSdk較低而使用 android.support.v4.app.Fragment,那麼 Activity 必須繼承 FragmentActivity、Manager 要用 getSupportFragmentManager();若使用原生 android.app.Fragment,則對應 getFragmentManager()。兩者混用會直接編譯失敗或執行期崩潰。
  • 不要在每次切換時重複 add 同一個 Fragment。用 null 判斷守住「第一次才 add」,後續一律 show,否則會疊出多個實例。
  • 記得處理返回鍵。若希望返回鍵能回到上一個頁籤而非直接離開,可在 onBackPressed() 中攔截並呼叫 setChioceItem()。
  • 狀態保存。橫屏或記憶體回收後 Activity 重建,Fragment 會被系統還原,但當前選中的頁籤樣式不會自動恢復。可在 onSaveInstanceState() 記錄 index,於 onCreate() 中還原。
  • 單頁籤時的效能。每個 Fragment 都常駐記憶體,若某頁的初始化很重(例如載入大圖或大量資料),可考慮懶載入:初次切換到該頁時才觸發資料請求。

以上就是 Fragment 實現底部導航欄的完整流程。程式碼量確實不多,但把 hide/show 的取捨、套件選擇與狀態還原想通,之後換成 ViewPager 搭配 FragmentPagerAdapter 也會輕鬆很多。

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