关于android layout_weight的疑问

来源:互联网 发布:华为麦芒5网络设置 编辑:程序博客网 时间:2024/05/10 12:42

layout_weight

linearLayout布局中,有一个属性为layout_weight,代表着权重。例如代码

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:orientation="horizontal"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    >

<TextView 

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:text="@string/hello"

    />

<Button

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:text="@string/button1"

    android:layout_weight="1"

/>

<Button

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:text="@string/button2"

    android:layout_weight="1"

/>

从代码中我们可以看出,布局应该是先让textView展开,然后对于剩余的空间,按照权重1:1分配给两个Button

(权重数字越小,说明占的空间越大,如果button1layout_weight=1,button2layout_weight=2,则说明剩余的空间2/3button1,1/3button2)。

但是,经过测试发现,这种说法并不是完全正确的。上面的代码,执行的当,@string/button1@string/button1长度相同时,确实正确。如图:

现在,我们将按钮2的字符串加长,出现的结果为:

我们明显的可以看到,textview的长度是没有任何变化的,但是两个按钮的长度却发生了很大的变化,这在代码编写过程中势必会引起误会。权重失效了吗?

从目测的结果来看,基本上是1/3的分配给了按钮1,2/3分配给了按钮2.造成这种现象的问题究竟是什么呢?

猜测:有按钮上字符串的个数我们可以明确的看到,如果都按照wrap_content都显示出来的话,按钮2一定是按钮1长度的两倍(这里假设手机屏幕足够长)。而这里权重的1:1应该是这种意思:

       假如剩余屏幕长度为a,按钮1wrap_content长度为b1,按钮2wrap_content长度为b2。那么这里的权重一比一,对按钮1来说应该是b1/a,对按钮2来说应该是b2/a,至于b1b2是否相等,那就不重要了。重要的是权重11的理解方式。

等待高人帮忙解答!

 

 

 

原创粉丝点击