当前位置: 移动互联网学院 > Android开发 > layout_weight使用方法
layout_weight使用方法 时间:2017-04-11     来源:Android开发学习网

layout_weight怎么用呢?今天和大家分享一下layout_weight的使用场景、使用方法和使用中经常会遇到的问题。

什么情况下会使用到layout_weight?

layout_weight意思是布局比重的意思,在线性布局中常用layout_weight分割布局。通常线性布局中宽高布局常用android:layout_width=match_parent|wrap_content,android_height=match_parent|wrap_content来进行布局,如果要用比重布局,通常android:layout_width属性就会不起作用,设置为"0";根据想要布局的比例,设定android:layout_weight的值,值越大,占的布局就越大。

layout_weight使用

首先我们要知道,只有在Linearlayout中该属性才有效。Android:layout_weight使用过程中常遇到的问题是设置layout_weight属性的同时,又设置了android:layout_width为wrap_content和match_parent,这样就会造成两种截然相反的效果。如下所示:

<LinearLayout

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:orientation="horizontal" >

<TextView

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_weight="1"

android:background="@android:color/black"

android:text="111"

android:textSize="20sp" />

<TextView

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_weight="2"

android:background="@android:color/holo_green_light"

android:text="222"

android:textSize="20sp" />

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

layout_weight使用方法1

权重为1的组件反而占了三分之二!

再看如下布局:

<LinearLayout

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:orientation="horizontal" >

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_weight="1"

android:background="@android:color/black"

android:text="111"

android:textSize="20sp" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_weight="2"

android:background="@android:color/holo_green_light"

android:text="222"

android:textSize="20sp" />

</LinearLayout>

即宽度为wrap_content,得到视图如下:

layout_weight使用方法2

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

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

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

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

以上就是对layout_weight如何使用的分享,更多Android开发技术文章请持续关注我们。