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

Android LinearLayout 權重均分失效:巢狀佈局缺少 orientation 屬性

     編輯:程式設計疑難解答

問題現象

使用 layout_weight 期望子視圖均分寬度/高度,但子視圖擠在一起,權重不生效。

根本原因

**第二層 (內層) LinearLayout 缺少 android:orientation 屬性**。LinearLayout 預設 orientation="horizontal",但若未顯式聲明,某些情況下權重計算異常;且巢狀佈局時,**父容器與子容器的 orientation 必須明確**,權重才按預期方向分配。

修正代碼

<!-- 外層垂直佈局 -->
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <!-- 內層水平佈局:必須顯式聲明 orientation -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="horizontal">  <!-- 關鍵屬性 -->

        <View
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1" />
        <View
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1" />
    </LinearLayout>
</LinearLayout>

權重生效三要素

  1. 子視圖對應方向尺寸設為 0dp (寬度用 weight 時 width=0dp,高度用 weight 時 height=0dp)。
  2. 父容器 orientation 與子視圖權重方向一致。
  3. 所有參與權重分配的兄弟視圖均設定 layout_weight。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved