編輯:關於 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 才是現行做法。
Android 如何播放 RTMP 直播流——Vitamio 庫實戰
本文將介紹如何在 Android 上基於 Real Time Messaging Protocol(RTMP)實現直播串流播放,並延伸說明 RTSP、m3u8(HLS)
Android AlertDialog 進階玩法:做出分享、退出、下載風格彈窗
摘要 彈窗常用來引導使用者做某個操作:點分享鈕彈出分享面板、雙擊返回鈕彈出退出確認、點下載彈出下載提示。這三種情境都能直接用 AlertDialog 完成。 一、Ale
Android 自訂控制項:實作 icon 與文字的多種排列效果
今天為大家帶來一個簡單卻相當實用的控制項 ButtonExtendM。在開發中,我們經常會用到圖片加文字的組合控制項,像這樣: 以上圖片皆擷取自微信(暫時還沒找到 ic
自訂 ListView 側滑刪除:仿 QQ 訊息列表的橫向滑動互動實作
從長按刪除到側滑刪除的改版起點最近參與的專案裡,ListView 的項目刪除一直沿用 Android 常見的長按或點擊方式。老闆看完之後覺得這樣的互動不夠直觀,於是提出了