美文网首页
Android的layout_weight属性

Android的layout_weight属性

作者: fishpan | 来源:发表于2017-04-15 21:48 被阅读21次

我们经常使用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子控件上才能生效

相关文章

网友评论

      本文标题:Android的layout_weight属性

      本文链接:https://www.haomeiwen.com/subject/zpsoattx.html