編輯:Android 資訊
FragmentTabHost 從 Android 4.0 起就進入原生控件,至今仍在大量項目中使用;5.0 之後又有了 TabLayout + ViewPager 這套新方案。本文聚焦前者,講清兩件事:自定義 Tab 外觀並去掉分割線,以及緩存 Fragment 視圖以減少重複 inflate。
關於緩存,要說明的背景是:切換頁面時控件會調用 Fragment 的 onCreateView 重建視圖,把結果緩存下來可以明顯提升流暢度。
FragmentTabHost 是原生控件,不需要引入任何第三方庫。結構分兩塊:標簽組 Tabs 固定高度,內容容器 TabContainer 佔滿剩餘空間。
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.app.FragmentTabHost
android:id="@android:id/tabhost"
xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TabWidget
android:id="@android:id/tabs"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_gravity="bottom" />
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
</android.support.v4.app.FragmentTabHost>這裡的 id 必須使用 Android 提供的標準 id,即 "@android:id" 形式,自定義 id 會導致控件無法正常工作。
Fragment 布局,一行居中文字:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/tab_tv_text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:textSize="40sp"
tools:text="Test" />
</LinearLayout>Tab 指示器布局,只放一個圖片:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="@+id/tab_iv_image"
android:padding="12dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="@null"
tools:src="@drawable/tab_assistant" />
</LinearLayout>setup 完成頁面組合,setDividerDrawable(null) 去掉分割線,然後逐個添加 Tab。newTabSpec 傳入的 tag 會成為後續 Fragment 的身份標識。
/**
* 主頁:切換 Tab 標簽顯示不同頁面
*/
public class MainActivity extends AppCompatActivity {
@Bind(android.R.id.tabhost) FragmentTabHost mTabHost;
@DrawableRes
private int mImages[] = {
R.drawable.tab_counter,
R.drawable.tab_assistant,
R.drawable.tab_contest,
R.drawable.tab_center
};
private String mFragmentTags[] = { "counter", "assistant", "contest", "center" };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
mTabHost.setup(this, getSupportFragmentManager(), android.R.id.tabcontent);
mTabHost.getTabWidget().setDividerDrawable(null); // 去掉分割線
for (int i = 0; i < mImages.length; i++) {
TabHost.TabSpec tabSpec =
mTabHost.newTabSpec(mFragmentTags[i]).setIndicator(getImageView(i));
mTabHost.addTab(tabSpec, FragmentTab.class, null);
mTabHost.getTabWidget().getChildAt(i)
.setBackgroundResource(R.color.pedo_actionbar_bkg);
}
}
/** 獲得圖片資源 */
private View getImageView(int index) {
@SuppressLint("InflateParams")
View view = getLayoutInflater().inflate(R.layout.view_tab_indicator, null);
ImageView imageView = view.findViewById(R.id.tab_iv_image);
imageView.setImageResource(mImages[index]);
return view;
}
}Fragment 通過 tag 顯示對應信息。緩存的關鍵細節是:複用之前必須先解除與舊父容器的關聯,否則 inflate 時會拋出「已有 parent」的異常。
public class FragmentTab extends Fragment {
@Bind(R.id.tab_tv_text) TextView mTvText;
private View mViewContent; // 緩存視圖內容
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
if (mViewContent == null) {
mViewContent = inflater.inflate(R.layout.fragment_tab, container, false);
}
// 緩存 View 若仍帶有 parent,必須先移除,否則會報「已有 parent」錯誤
ViewGroup parent = (ViewGroup) mViewContent.getParent();
if (parent != null) {
parent.removeView(mViewContent);
}
ButterKnife.bind(this, mViewContent);
return mViewContent;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mTvText.setText("Page: " + getTag());
}
@Override
public void onDestroyView() {
super.onDestroyView();
ButterKnife.unbind(this);
}
}效果如下:

幾個容易踩到的點值得再強調一遍:三個 id 必須是系統標準 id;自定義 Tab 樣式通過 setIndicator(View) 注入;緩存方案要在 onDestroyView 中解綁 ButterKnife,避免持有已銷毀的視圖引用。
熟練掌握這幾個要點,FragmentTabHost 依然是快速搭建多頁結構的可靠選擇。
Android Flux 架構入門:單向資料流如何組織應用
從 MVC、MVP 到 FluxAndroid 應用的架構演進,本質上是在回答一個問題:如何讓界面、業務邏輯與資料狀態之間保持清晰邊界。MVC 與 MVP 都曾經是常見方
以 MediaPlayer 為例,透視 Android Framework 層的 JNI 運作機制
JNI(Java Native Interface,本地呼叫介面)對寫 Java 的人來說不陌生,主要功能就兩項:讓 Java 層呼叫 C/C++,以及讓 C/C++ 回
Android 換膚方案實作:把皮膚做成獨立 APK 動態載入
這篇筆記分享一個 Android 換膚的 Demo 思路與完整實作,程式碼已整理上傳到我的 GitHub,後續文章涉及的程式碼也都會統一放在那裡管理。 GitHub 位址
Mono for Android 下的 ListActivity 使用介紹
簡介 ListActivity 是 Android 中常用的列表頁面基礎類別。在 Mono for Android 中,可以透過 ArrayAdapter、字串資源與自訂