android: android 布局中的weight 屬性


android: weight是線性布局的特有屬性,控件的寬度和高度的不同,也會存在差異。

示例1:將寬度設置為包裹類型wrap_content或0dp

<?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"
    tools:context=".WeightApiUseDemoActivity"
    android:orientation="horizontal"
    >

    <Button
        android:layout_width="0dip"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Button 1"
        />

    <Button
        android:layout_width="0dip"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:text="Button 2"
        />

</LinearLayout>

運行:

 

示例2: 將寬度設置為match_parent時

<?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"
    tools:context=".WeightApiUseDemoActivity"
    android:orientation="horizontal"
    >

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Button 1"
        />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:text="Button 2"
        />

</LinearLayout>

運行:

 

 

小結: 第一種現象很好理解,當放置兩個寬度為0dip或是wrap_content的按鈕時,由於寬度並未確定,那Button1所占的寬度就是 1 / (1+2) = 1/ 3, 也就是總長度的1/3;Button2 所占的寬度是 2 / (1+2) = 2 / 3, 也就是總長度的2/3。

第二種現象就很奇怪了,其實這是因為View在繪制的時候有一個規則,如果給View添加了android:weight屬性,那么這個View的最終寬度 = View本來定義的寬度 +   View在LinearLayout中剩余空間中所占比例的寬度。什么意思呢,假設線性布局的總寬度為 L ,

拿第一種現象來說

Button1的寬度 = 0dip + ( L - Button1的寬度(也就是0dip) - Button2的寬度(也是0dip) ) * 1/3 = 0dip + L * 1/3 = 1/3 L。
Button2的寬度 =  0dip + ( L - Button1的寬度(也就是0dip) - Button2的寬度(也是0dip) ) * 2/3 = 0dip + L * 2/3 = 2/3 L。

拿第二種現象來說

Button1的寬度 = L + ( L - Button1的寬度(也就是L) - Button2的寬度(也是L) ) * 1/3 = L + (-L) * 1/3 = L - 1/3 L = 2/ 3L。
Button2的寬度 = L + ( L - Button1的寬度(也就是L) - Button2的寬度(也是L) ) * 2/3 = L + (-L) * 2/3 = L - 2/3 L = 1/ 3L。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM