1. 程式人生 > >Android 螢幕適配之weight的使用

Android 螢幕適配之weight的使用

1. 要點:必須在LinearLayout的佈局內使用才有效果
2. 計算公式:
控制元件寬度=控制元件原始寬度+權重比例xLinearLayout剩餘寬度。
3. 實踐:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:
layout_height="match_parent" android:orientation="vertical" tools:context="com.example.android_develop_advance.MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:
layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="width_0dp_weight_1" /> <Button android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="2" android:
text="width_0dp_weight_2" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:text="width_math_weight_1"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="2" android:text="width_math_weight_2"/> </LinearLayout> </LinearLayout>

在這裡插入圖片描述
5. 計算:
控制元件寬度=控制元件原始寬度+權重比例xLinearLayout剩餘寬度。
第一部分控制元件原始寬度:0dp
剩餘寬度:螢幕寬度
權重:1/3 和2/3
width_0dp_weight_1控制元件的寬度= 0 + 1/3 x 螢幕寬度 = 1/3螢幕寬度
width_0dp_weight_2控制元件的寬度= 0 + 2/3 x 螢幕寬度 = 2/3螢幕寬度
第二部分控制元件原始寬度:match_parment
剩餘寬度:螢幕寬度- 兩個控制元件寬度(即兩個螢幕寬度) = -螢幕寬度
權重:1/3 和2/3
width_match_weight_1控制元件的寬度= 螢幕寬度 + 1/3 x(- 螢幕寬度) = 2/3螢幕寬
width_match_weight_2控制元件的寬度= 螢幕寬度 + 2/3 x (-螢幕寬度) = 1/3螢幕寬度