標籤:android blog http java strong width
本文主要介紹
Android LinearLayout的android:layout_weight屬性意義
android:layout_weight為大小權重,相當於在頁面上顯示的百分比,它的計算是根據LinearLayout中所有相關元素的此屬性值計算的。
除了已經固定大小的,其他設定了此屬性的view所佔大小(長度或高度)為自己layout_weight屬性值/所有layout_weight屬性值*總大小。這個屬性在android的sdk中都沒有介紹。下面舉例介紹下
比如在一個layout中顯示3個TextView,第一個TextView長度佔20%,第二個長度佔50%,第三個占長度30%,
則比例為20%:50%:30%=2:5:3。layout代碼如下
Java代碼
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent">
- <TextView android:id="@+id/textView1"
- android:layout_width="wrap_content"
- android:layout_height="match_parent"
- android:layout_weight="2"
- android:layout_alignParentLeft="true"
- android:gravity="center_vertical"
- android:text="文本1" />
- <TextView android:id="@+id/textView2"
- android:layout_width="wrap_content"
- android:layout_height="match_parent"
- android:layout_weight="5"
- android:layout_alignParentLeft="true"
- android:gravity="center_vertical"
- android:text="文本2" />
- <TextView android:id="@+id/textView3"
- android:layout_width="wrap_content"
- android:layout_height="match_parent"
- android:layout_weight="3"
- android:layout_alignParentLeft="true"
- android:gravity="center_vertical"
- android:text="文本3" />
- </LinearLayout>
從以上代碼可以看出只需要設定各個TextView的android:layout_weight屬性值為對應的比例即可
其中android:layout_alignParentLeft="true" android:gravity="center_vertical"是為了方便查看而設定