Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

layout_weight 屬性圖解:三種常見的權重分配用法

編輯:關於 Android 開發

layout_weight 的作用

它會先按照各控件聲明的尺寸進行分配,再將剩餘空間依據 layout_weight 的比例進行分配。

一、平均分配


程式碼:

<LinearLayout android:gravity="center" android:layout_height="wrap_content" android:layout_width="match_parent" android:orientation="horizontal" xmlns:android="https://schemas.android.com/apk/res/android"> <TextView android:background="#e1d611" android:gravity="center" android:layout_height="50dp" android:layout_weight="1" android:layout_width="0dp" android:text="我是老大我是老大我是老大" android:textColor="#ffffff" android:visibility="gone"> <TextView android:background="#09c0f2" android:gravity="center" android:layout_height="50dp" android:layout_weight="1" android:layout_width="0dp" android:text="我是老二" android:textColor="#ffffff"> <TextView android:background="#074bc1" android:gravity="center" android:layout_height="50dp" android:layout_weight="1" android:layout_width="0dp" android:text="我是老三" android:textColor="#ffffff" android:visibility="gone"> </TextView></TextView></TextView></LinearLayout>

二、平均且對齊


在父控件中加上:

android:baselineAligned="false"

三、單個分配比例


在父控件中加入:

android:weightSum="2"

程式碼:

<LinearLayout android:baselineAligned="false" android:gravity="center" android:layout_height="wrap_content" android:layout_width="match_parent" android:orientation="horizontal" android:weightSum="2" xmlns:android="https://schemas.android.com/apk/res/android"> <TextView android:background="#09c0f2" android:gravity="center" android:layout_height="50dp" android:layout_weight="1" android:layout_width="0dp" android:text="我是老二" android:textColor="#ffffff"> </TextView></LinearLayout>
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved