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

Android 新手教程:底部三等分 Button 佈局實現(LinearLayout + weight)

     編輯:程式設計疑難解答

需求分析

底部固定三個 Button,寬度均分螢幕 1/3,無間隙,類似 Tab 效果。

核心屬性:layout_weight + weightSum

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:orientation="horizontal"
    android:weightSum="3">

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="首頁"
        android:background="@null"
        android:padding="16dp"/>

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="發現"
        android:background="@null"
        android:padding="16dp"/>

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="我的"
        android:background="@null"
        android:padding="16dp"/>

</LinearLayout>

關鍵點解析

屬性值作用
layout_width0dp寬度由 weight 決定,忽略 wrap_content
layout_weight1三個各佔 1 份,共 3 份 → 各 1/3
weightSum3父佈局聲明總份數,避免子 View 計算誤差
background@null移除預設灰色背景與邊框線
layout_gravitybottom整組靠底(若在 CoordinatorLayout/FrameLayout 中)

進階:替換為 Material BottomNavigationView

<com.google.android.material.bottomnavigation.BottomNavigationView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    app:menu="@menu/bottom_nav_menu"
    app:labelVisibilityMode="labeled"
    app:itemBackground="@color/white"/>

優點:內建選中狀態、圖標+文字、Badge、動畫、無障礙支援,符合 Material Design 規範。

總結

新手首選 LinearLayout + weightSum=3, weight=1, width=0dp,簡單可控;項目正式上線建議遷移至 BottomNavigationView,獲得完整的交互體驗與無障礙支援。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved