Android学习之LinearLayout比例布局计算

3,008 阅读1分钟

LinearLayout布局关键的三个属性是:

1、layout_width

2、layout_height

3、layout_weight

宽高一般采用wrap_content或match_parent

看看下面xml布局

<LinearLayout xmls:android="http://schemas.android.com/apk/res/android"
xmlsn:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView 
       android:layout_weight="1"
       android:layout_width="wrap_content"
       android:layout_height="match_parent"
       android:text="one"
       android:background="#FFFF00"      
/>
<TextView 
       android:layout_weight="2"
       android:layout_width="wrap_content"
       android:layout_height="match_parent"
       android:text="one"
       android:background="#FF0000"      
/>
<TextView 
       android:layout_weight="3"
       android:layout_width="wrap_content"
       android:layout_height="match_parent"
       android:text="one"
       android:background="#00FF00"      
/></LinearLayout>

上面宽度采取的是wrap_content的方式,最后呈现的视图比例是1:2:3

如果把上面的layout_width换成match_parent呢,最后的比例还是1:2:3吗?

可以运行一下,结果的比例是2:1:0,在网上看到一个计算公式,

此种情况下布局比例 = 父容器空间大小 + 权重比例 * 剩余空间大小

可以参考以下计算过程进行理解

1、3个都是match_parent,但是屏幕只有一个,剩余空间大小是 1 -3 = -2

2、第一个 1 + 1/6*(1-3) = 2/3

3、第二个 1 + 2/6*(1-3) = 1/3

4、第三个 1 + 3/6 * (1-3) = 0

结果是 2 :1 : 0