Android的layout_weight属性

我们经常使用layout_weight设置LinearLayout子控件的高度和宽度的占比,那子控件的高度和宽度究竟是怎么计算的?

<LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="50dp">
    <TextView
        android:background="#da5845"
        android:layout_weight="3"
        android:layout_width="0dp"
        android:layout_height="match_parent"/>

    <TextView
        android:background="#4577dc"
        android:layout_weight="2"
        android:layout_width="0dp"
        android:layout_height="match_parent"/>
</LinearLayout>

效果图如下:



红色占2/5,蓝色占3/5

<LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="50dp">
    <TextView
        android:background="#da5845"
        android:layout_weight="3"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <TextView
        android:background="#4577dc"
        android:layout_weight="2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>

红色占2/5,蓝色占3/5

OK,那layout_weight的真正含义是当控件设置了此属性,那么控件高度或者宽度为自身的高度或宽度加上剩余空间的占比。
以第二段代码为例,假设屏幕的宽度为W,两个子控件的宽度都是match_parent,那么剩余的空间为W - 2W = -W,第一个子控件的宽度为W + (-W * 3 / 5 ) = W * 2 / 5;同理第二个子控件的宽度为W * 3 / 5。

注意:layout_weight只有在LinearLayout子控件上才能生效

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容