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

Android 布局技巧:標題欄+內容區+底部欄,中間 FrameLayout 自適應填滿剩餘空間

     編輯:程式設計綜合問答

經典需求:頂部固定高度標題欄、底部固定高度底部欄、中間 FrameLayout 自動填滿剩餘高度。

核心屬性:layout_weight="1" + layout_height="0dp"

<LinearLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <!-- 頂部標題欄:固定高度 -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:background="?attr/colorPrimary"
        android:gravity="center_vertical"
        android:paddingHorizontal="16dp">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="標題"
            android:textSize="20sp"
            android:textColor="@android:color/white"/>
    </LinearLayout>

    <!-- 中間內容區:佔據剩餘空間 -->
    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <!-- 底部欄:固定高度 -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:background="@android:color/white"
        android:gravity="center"
        android:orientation="horizontal">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="底部資訊" />
    </LinearLayout>

</LinearLayout>

原理解析

  • 父容器 LinearLayout 垂直排列,總高 match_parent。
  • 標題欄、底部欄指定具體 layout_height(如 56dp、48dp)。
  • 中間 FrameLayout 設 layout_height="0dp" 並 layout_weight="1",告訴佈局系統:「先分配固定高度給兄弟元素,剩餘空間全給我」。

同理可用 ConstraintLayout 配合 app:layout_constraintTop_toBottomOf/Bottom_toTopOf 實現,效能更優、層級更淺。

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