首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android TabHost TabWidget 平均分佈:解決標籤無法平鋪底部問題

     編輯:程式設計綜合問答

現象描述

使用 TabHost + TabWidget 時,設定 layout_width="match_parent" 標籤擠在左側;改為 wrap_content 則寬度不一,無法平均分佈。

核心原因

TabWidget 繼承 LinearLayout,但預設不自動分配子視圖寬度,需手動計算螢幕寬度並設定每個分頁的 LayoutParams。

解決方案:程式碼動態設定寬度

private void setTabWidths(TabWidget tabWidget) {
    WindowManager wm = getWindowManager();
    Display display = wm.getDefaultDisplay();
    int screenWidth = display.getWidth();
    int tabCount = tabWidget.getChildCount();
    int tabWidth = screenWidth / tabCount;

    for (int i = 0; i < tabCount; i++) {
        View tabView = tabWidget.getChildAt(i);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(tabWidth, LinearLayout.LayoutParams.MATCH_PARENT);
        tabView.setLayoutParams(params);
    }
}

// 在 onCreate 或 setContentView 後呼叫
setTabWidths((TabWidget) findViewById(android.R.id.tabs));

進階:使用 TabLayout (Material Design)

現代應用建議改用 com.google.android.material.tabs.TabLayout 搭配 ViewPager2,原生支援 tabMode="fixed" 與 tabGravity="fill" 實現完美平鋪:

<com.google.android.material.tabs.TabLayout
    android:id="@+id/tabLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tabMode="fixed"
    app:tabGravity="fill" />

注意事項

  • 動態設定寬度需在 TabWidget 子視圖已建立後執行(如 setup() 之後)。
  • 若分頁標題過長,考慮縮短文字或啟用 android:singleLine="true" + android:ellipsize="end"。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved