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

Android 底部標籤頁實作:以 Fragment 切換多個分頁

編輯:關於 Android 程式設計

前言

底部標籤頁是很常見的 UI 模式,微信就是最典型的例子——既可以點擊標籤切換,也能左右滑動。本文先聚焦在比較基礎的部分:如何透過點擊底部標籤切換 Fragment。

先看要達成的效果:

版面結構

整個畫面可以切成三塊:頂部導覽列、中間內容區、底部標籤列。中間內容區用 FrameLayout 當容器,讓 Fragment 有地方安放:

activity_main.xml

<FrameLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/content_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

切換的核心邏輯

初始狀態是第一個標籤被選中,圖示與文字顏色都和其他兩個不同。所以切換時要做兩件事:改三個標籤的圖片與文字顏色,以及替換顯示的 Fragment。

三個 Fragment 分別對應各自的版面檔:

ZhidaoFragment.java → main_tab1_fragment.xml
IWantKnowFragment.java → main_tab2_fragment.xml
MeFragment.java → main_tab3_fragment.xml

Fragment 的切換用 add / hide / show 的組合最有效率——不要每次都 remove 再 add,那樣會重建 View,既慢又會丟失狀態:

/**
 * 添加或顯示 Fragment
 */
private void addOrShowFragment(FragmentTransaction transaction, Fragment fragment) {
    if (currentFragment == fragment) return;

    if (!fragment.isAdded()) {
        // 尚未加入過,先隱藏目前這頁再加入新的
        transaction.hide(currentFragment)
                .add(R.id.content_layout, fragment).commit();
    } else {
        // 已加入過,直接切換可見性
        transaction.hide(currentFragment).show(fragment).commit();
    }
    currentFragment = fragment;
}

這段寫法有個關鍵細節:第一次加入時必須先 hide(currentFragment),因為新 Fragment 被 add 進容器後預設就是可見的,若不先藏起舊的,兩頁會疊在一起。

完整程式碼

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 */
public class MainActivity extends FragmentActivity implements OnClickListener {

    // 三個 tab 的容器
    private RelativeLayout knowLayout, iWantKnowLayout, meLayout;
    // 底部標籤對應的 Fragment,currentFragment 記錄目前顯示的那頁
    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();
    }

    /** 初始化元件 */
    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();
            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);

        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));
    }

    /** 添加或顯示 Fragment */
    private void addOrShowFragment(FragmentTransaction transaction, Fragment fragment) {
        if (currentFragment == fragment) return;

        if (!fragment.isAdded()) {
            transaction.hide(currentFragment)
                    .add(R.id.content_layout, fragment).commit();
        } else {
            transaction.hide(currentFragment).show(fragment).commit();
        }
        currentFragment = fragment;
    }
}

可以簡化的地方

上面三個 clickTabNLayout() 幾乎是同一段程式複製三次,只差在索引。實務上建議收斂成一個方法,把標籤的圖示與 Fragment 放進陣列,用 position 統一處理:

private void switchTab(int position) {
    Fragment target = fragments[position];
    addOrShowFragment(getSupportFragmentManager().beginTransaction(), target);

    for (int i = 0; i < tabs.length; i++) {
        boolean selected = (i == position);
        tabs[i].image.setImageResource(selected ? iconsPre[i] : iconsNor[i]);
        tabs[i].text.setTextColor(getResources().getColor(
                selected ? R.color.bottomtab_press : R.color.bottomtab_normal));
    }
}

標籤數量一旦超過三個,複製貼上的維護成本會急遽上升,及早抽成迴圈會輕鬆很多。

另外兩點值得注意。getResources().getColor() 不帶 theme 的重載版本已標記為 deprecated,建議改用 ContextCompat.getColor(context, R.color.xxx)。以及,每個 Fragment 的版面都應該在 onCreateView() 中建立,不要依賴 setRetainInstance() 這類舊 API 來保存狀態,改用 ViewModel 才是現行做法。

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