android:layout_weight的含义

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="horizontal"
        >

    <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="hello_world"/>
    <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="button"
            />

</LinearLayout>

在android布局中,有时候希望按照比例去占用屏幕空间,就有了 android:layout_weight属性,但是这个属性仅仅是在Linearlayout布局中有用。

刚刚写了布局的时候,发现个问题。将两个view的宽度都设置成0dp,这两个view会平分屏幕宽度,设置成wrap_content,也是一样的效果,无意间随便改动一个view的宽度的时候,在预览的时候,会发现宽度变化了。

原来,假如宽度两个都设置成0dp,那么两个view正好平分了,而设置成wrap_content的时候,是先计算出自己本身需要的控件宽度,而后再按照比例分担剩余的空间,一定是剩余的!

不信,可以将其中一个view的字符加长,就会发现明显的变化。,


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="horizontal"
        >

    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="hello_world1111111111111111111111111111111111111111111111"/>
    <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="button"
            />

</LinearLayout>

会发现,即使都是warp,都是权重为1,但是占据的空间宽度不一样。


而如果都是0dp 呢,那的确是在平分了,为何?因为剩余的空间是整个屏幕.


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="horizontal"
        >

    <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="hello_world1111111111111111111111111111111111111111111111"/>
    <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="button"
            />

</LinearLayout>




总结,

1.权重的使用,肯定是在线性布局中的。

2.按照自己的需求,是否是需要整体达到一定的比例分配,是,则设置成0dp;如果希望首先考虑其中一个要显示完全,将这个view设置成wrap,

3.分配的时候,首先是计算控件本身的宽度,然后再计算剩余的空间分配。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值