Android之权重layout_weight的真正用法

Android之权重layout_weight的真正用法layout_weigh——权重总的来说就是屏幕的剩余空间按比例分配首先声明只有在Linearlayout中,该属性才有效。之所以android:layout_weight会引起争议,是因为在设置该属性的同时,设置android:layout_width为wrap_content和match_parent会造成两种截然相反的效果。LinearLayout为水平的时候和垂直都是一样的效果,现在讨

大家好,欢迎来到IT知识分享网。

layout_weigh——权重  总的来说就是屏幕的剩余空间按比例分配

首先声明只有在Linearlayout中,该属性才有效。之所以android:layout_weight会引起争议,是因为在设置该属性的同时,设置android:layout_width为wrap_content和match_parent会造成两种截然相反的效果。LinearLayout为水平的时候和垂直都是一样的效果,现在讨论为水平的时候的效果。

如下所示:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns: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:background="#ff0000"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="11111" />
    <TextView
        android:layout_weight="3"
        android:background="#00ff00"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="33333" />

</LinearLayout>

上面的布局将两个TextView的宽度均设为match_parent,一个权重为1,一个权重为3.得到效果如下:

Android之权重layout_weight的真正用法

可以看到权重为1的反而占了四分之三!

再看如下布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns: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:background="#ff0000"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="11111" />
    <TextView
        android:layout_weight="3"
        android:background="#00ff00"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="33333" />

</LinearLayout>

宽度为wrap_content,效果如下图:

Android之权重layout_weight的真正用法

左边 TextView占比四分之一,又正常了。

android:layout_weight的真实含义是:一旦View设置了该属性(假设有效的情况下),那么该 View的宽度等于原有宽度(android:layout_width)加上剩余空间的占比!

设屏幕宽度为L,在两个view的宽度都为match_parent的情况下,原有宽度为L,两个的View的宽度都为L,那么剩余宽度为L-(L+L) = -L, 左边的View占比四分之三,左边的总宽度是L+(-L)*1/4 = (3/4)L.事实上默认的View的weight这个值为0,一旦设置了这个值,那么所在view在绘制的时候执行onMeasure两次的原因就在这。

Google官方推荐,当使用weight属性时,将width设为0dip即可,效果跟设成wrap_content是一样的。这样weight就可以理解为占比了!




免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/21148.html

(0)

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

关注微信