Android layout_weight属性的工作原理

这篇文档主要讲一下layout_weight。给组件添加这个属性时,有一点需要注意,在Android studio中,Design中显示的布局会和手机上运行时显示的不一样,不要被Design蒙骗。

先上一段局部布局代码,和一张手机界面截图

局部代码

    <TextView
        style="?android:listSeparatorTextViewStyle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/crime_details_label"
        />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        >

        <Button
            android:id="@+id/crime_date"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            />
        <CheckBox
            android:id="@+id/crime_solved"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/crime_solved_label"
            />
    </LinearLayout>

</LinearLayout>

 

 

 

手机界面截图



从这些信息中,我们可以发现,当LinearLayout中的组件android:layout_width=”wrap_content”时,即便两个android:layout_weight都等于1,从手机上可以看到,比例并不一样,如果从Android studio Design上看呢?

 

Android studio Design



 

 

大家可以发现,是一样的,到底哪个是对的呢?理论上来说是手机,下面我就要来讲解一下layout_weight属性的原理。

LinearLayout是分两个步骤来设置属性宽度的,第一步是查看layout_width的属性值,也就是说它会优先考虑layout_width的属性值,第二步是根据layout_weight属性值进行额外的空间分配,通俗点说,只要layout_width发话了,就全听layout_width的(其实也不是,layout_weight会有影响),如果layout_width没有发话,两个layout_width的值被设置为0dp,

布局按照第二步的设置来安排。


下面我们就来这么做,把layout_width设置成0dp,两个组件的layout_weight还都是1不变,上代码,Design图,手机界面截图。

局部代码

 

  <TextView
        style="?android:listSeparatorTextViewStyle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/crime_details_label"
        />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        >

        <Button
            android:id="@+id/crime_date"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            />

        <CheckBox
            android:id="@+id/crime_solved"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/crime_solved_label"
            />
    </LinearLayout>

</LinearLayout>

 

 

Android studio Design:



当然,它还是保持不变。

 

 

手机界面截图



 

通过这两个实验,我们知道它的属性设置是有优先级的。





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值