本文转载自http://sinye.iteye.com/blog/1068204
android
在网上看了一些对Layout_weight的讲解,有些说的比较片面,只列举了一种状况,而后本身经过实验和一些比较好的文章总结了一下,特此记录下来,以备之后所用。Layout_weight是线性布局,也就是LinearLayout里面用到的,下面经过实验来看这个Layout_weight的特性。ide
1.当控件的属性android:layout_width="fill_parent"时,布局文件以下:布局
<?xmlversion="1.0"encoding="utf-8"?> <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal"android:layout_width="fill_parent" android:layout_height="fill_parent"> <Buttonandroid:layout_width="fill_parent" android:layout_height="wrap_content"android:layout_weight="1" android:text="Button1"/> <Buttonandroid:layout_width="fill_parent" android:layout_height="wrap_content"android:layout_weight="2" android:text="Button2"/> </LinearLayout>
在这里Button1的Layout_weight=1,Buttong2的Layout_weight=2,运行效果为:spa
咱们看到,Button1占了2/3,Button2占了1/3。若是此时把button2的weight设置成2000,不是说Button2就消失了,而是Button1的宽度几乎占满了屏幕宽度,而屏幕最后一丝细条则是留给Button2的,已近很是小了,没有显示出来。截图以下:设计
得出结论:在layout_width设置为fill_parent的时候,layout_weight表明的是你的控件要优先尽量的大,但尽量大是有限度的,即fill_parent.xml
2.当控件的属性android:layout_width="wrap_content"时,布局文件以下:blog
这时,和fill_parent正好相反,Button1的宽度占据了屏幕宽度的1/3,而Button2的宽度占据了屏幕的2/3,若是此时把Button1的weight设置为2000,按照以前理解,Button1应该小的几乎在屏幕上看不到,可是错了,实验告诉咱们,当Button1的weight很是小时,也要"wrap_content",也就是要保证Button1至少可以显示。如下是Button1设置weight为2000时的运行截图:get
咱们看到,Button1已经足够小,可是要保证他能显示出来,所以得出结论:
在layout_width设置为wrap_content的时候,layout_weight表明的是你的控件要优先尽量的小,但这个小是有限度的,即wrap_content.
当了解这些后,咱们再设计程序时,为了可以自适应屏幕,不想给控件一个指定的宽度和高度,就可使用这个weight属性来让它按本身比例来划分屏幕高度或者宽度了。