一直对layout_weight属性感到比较困惑,今天学习一下,来深入了解layout_weight属性和它的用法。
首先,看看Android官方文档是怎么说的,毕竟人家才是权威嘛。

官方文档的意思是:
layout_weight属性用于分配LinearLayout中的的额外空间(extra space)。
如果View不想拉伸的话,layout_weight值设置为0。否则的话这些像素会按比例分配到
这些weight值大于0的所有View。
换句话说,也就是android:layout_weight属性告知LinearLayout如何进行子组件的布置安排。
说这么多,不如用几个例子来形象的描述它:
1.首先设置一个Linear_Layout布局,方向设置为水平,放置两个TextView,不设置Layout_weight值。可以看到
空余的白色部分就是官方文档中所说的extra space(额外空间)。

布局文件代码:
1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
2 xmlns:tools="http://schemas.android.com/tools"
3 android:layout_width="match_parent"
4 android:layout_height="wrap_content"
5 android:orientation="horizontal" >
6
7 <TextView
8 android:layout_width="wrap_content"
9 android:layout_height="wrap_content"
10 android:background="#f00"
11 android:text="TextView1" />
12 <TextView
13 android:layout_width="wrap_content"
14 android:layout_height="wrap_content"
15 android:background="#0f0"
16 android:text="ThisIsTextView2"
17 />
18 </LinearLayout>
2.设置两个TextView的Layout_weight的值都为1。
在上面的xml文件中,给每个TextView增加一个"android:layout_weight=1"属性。

TextView1,TextView2的layout_weight值分别设置为2和1,1和2,看运行的效果:
2和1:

1和2:

相信通过以上例子和图片,大家应该对layout_weight属性的用法已经非常理解了。
那么,问题又来了。如果我想要将两个子组件分配相同的宽度或高度,那该怎么设置layout_weight呢?
只需要将各子组件的layout_width值设置为0,这样就避开了第一步的空间分配。
这样LinearLayout就只会考虑使用layout_weight值来完成空间的分配了。
1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
2 xmlns:tools="http://schemas.android.com/tools"
3 android:layout_width="match_parent"
4 android:layout_height="wrap_content"
5 android:orientation="horizontal" >
6
7 <TextView
8 android:layout_width="0dp"<!--将layout_width值设置为0dp以避开第一步的空间分配-->
9 android:layout_height="wrap_content"
10 android:background="#f00"
11 android:layout_weight="1"<!--LinearLayout将会按此值分配空间-->
12 android:text="TextView1" />
13 <TextView
14 android:layout_width="0dp"
15 android:layout_height="wrap_content"
16 android:background="#0f0"
17 android:layout_weight="1"
18 android:text="ThisIsTextView2"
19 />
20 </LinearLayout>

希望这篇文章对大家有所帮助,如果喜欢,请推荐,谢谢~
如果转载,请在文章开头处注明本博客地址:http:www.cnblogs.com/JohnTsai
欢迎讨论交流,邮箱:JohnTsai.Work@gmail.com