在 Android 早期 TabHost(已棄用,建議遷移至 ViewPager + TabLayout)中,調整 Tab 高度與文字垂直對齊需通過代碼動態設置或 XML 屬性。
TabHost tabHost = getTabHost();
// 設置第 0 個 Tab 高度為 40dp
int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 40, getResources().getDisplayMetrics());
tabHost.getTabWidget().getChildAt(0).getLayoutParams().height = height;
// 或遍歷所有 Tab 統一設置
for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {
tabHost.getTabWidget().getChildAt(i).getLayoutParams().height = height;
}
自定義 Tab 指示器佈局 res/layout/custom_tab_indicator.xml:
<TextView xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@android:id/title" <!-- 必須使用此 ID 系統才識別 -->
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center_vertical|top" <!-- 垂直居中+靠頂 或 center_vertical -->
android:textSize="12sp"
android:textColor="@android:color/white"
android:paddingTop="4dp"
android:paddingBottom="4dp" />
應用:
TabHost.TabSpec spec = tabHost.newTabSpec("tab1")
.setIndicator(getLayoutInflater().inflate(R.layout.custom_tab_indicator, null))
.setContent(intent);
for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {
View tabView = tabHost.getTabWidget().getChildAt(i);
// 尋找標題 TextView (系統內部 ID)
TextView titleView = tabView.findViewById(android.R.id.title);
if (titleView != null) {
titleView.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.TOP);
titleView.setPadding(titleView.getPaddingLeft(), 4, titleView.getPaddingRight(), 4);
}
}
<TabHost xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost"
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="wrap_content"
android:tabStripEnabled="false" /> <!-- 隱藏分割線 -->
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</TabHost>
TabHost 早已棄用,新專案請使用:
<!-- build.gradle -->
implementation "com.google.android.material:material:1.9.0"
// 佈局
<com.google.android.material.tabs.TabLayout
android:id="@+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="fill"
app:tabMode="fixed" />
<androidx.viewpager2.widget.ViewPager2
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
// 代碼
TabLayoutMediator mediator = new TabLayoutMediator(tabLayout, viewPager2, (tab, position) -> {
tab.setText(titles[position]);
// 自定義 Tab 視圖
// tab.setCustomView(customView);
});
mediator.attach();
優勢:Material Design 風格、自動適配、支持滾動/固定模式、Kotlin 協程友好、無需手動管理 Fragment 事務。