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

Android 適配不同螢幕分辨率:LinearLayout weight 比例佈局核心技巧

     編輯:程式設計綜合問答

問題本質

固定像素(`dp`/`px`)在不同密度螢幕上物理尺寸不同,導致元素超出可視區或留白過大。

核心方案:`LinearLayout` + `layout_weight` 比例分配

XML 示例

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

    <!-- 頂部固定高度 -->
    <View android:layout_width="match_parent"
          android:layout_height="56dp" />

    <!-- 中間列表佔剩餘空間 70% -->
    <RecyclerView
        android:id="@+id/rv_list"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="0.7" />

    <!-- 底部操作欄佔 30% -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="0.3"
        android:orientation="horizontal">
        <Button android:layout_width="0dp"
              android:layout_height="wrap_content"
              android:layout_weight="1"
              android:text="取消" />
        <Button android:layout_width="0dp"
              android:layout_height="wrap_content"
              android:layout_weight="1"
              android:text="確定" />
    </LinearLayout>

</LinearLayout>

關鍵規則

  1. **方向一致**:父 `orientation="vertical"` → 子 `layout_height="0dp"` + `layout_weight`;水平則 `layout_width="0dp"`。
  2. **權重和無需為 1**:`0.7` + `0.3` = 1 只是習慣,`2` + `1` 同樣 2:1 分配。
  3. **嵌套使用**:複雜界面層層拆分,每層只負責一維比例。

進階適配技巧組合拳

技術適用場景核心 API
最小寬度限定符針對 320dp/360dp/411dp/600dp/720dp 等斷點提供不同佈局`res/layout-sw360dp/` `res/layout-sw600dp/`
百分比佈局更直觀的百分比屬性(已棄用,建議用 ConstraintLayout + Guideline)`PercentRelativeLayout` / `ConstraintLayout` `app:layout_constraintWidth_percent`
ConstraintLayout 鏈複雜相對定位、鏈式分佈、佔比`app:layout_constraintHorizontal_chainStyle="spread_inside"`
VectorDrawable / WebP圖標、插圖無損縮放`android:src="@drawable/ic_vector"`
字體縮放 sp文字跟隨系統字體大小設置`android:textSize="16sp"`

原回答補充

原最佳回答「利用線性佈局特性,設置比例 weight 就可以解決」方向正確,上文提供完整 XML 範例、關鍵規則、進階組合拳表供直接落地。

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