<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#000000"
android:orientation="horizontal" >
<Button
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_weight="1"
android:text="Btn_Left" />
<Button
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_weight="2"
android:text="Btn_Right" />
</LinearLayout>
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#000000"
android:orientation="horizontal" >
<Button
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_weight="1"
android:text="Btn_Left" />
<Button
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_weight="2"
android:text="Btn_Right" />
</LinearLayout>
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#000000"
android:orientation="horizontal" >
<Button
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="1"
android:text="Btn_Left" />
<Button
android:layout_width="wrap_content"
android:layout_height="50dp"
android:text="Btn_Right" />
</LinearLayout>
Right按钮宽度为wrap_content,Left的宽度占剩下的所有
概括一下:“因为设置了button1的权重最小,所以它占用的布局优先级就越高”。(也许在Android里面布局并没有优先级之说,我这里只是为了说明问题)
当layout_width属性设置为fill_parent的时候,即充满父布局,当然意思是这个控件要根据weight的设置尽可能的大,因此,依上例而论,button1的weight设为1,button2的weight设置为2。即button1的优先级高,因此,要填充父布局就要button1先来填充,尽可能的大,那这个尽可能又是多少呢,这就要综合layout里其他控件的weight值了,然后做一下运算,button1占据2/3,button2占据1/3。你也可以把button2设置为一个非常大的数,比如2000,此时可以看到button1填充满了整个宽度,而看不到button2的影子,事实上button2还是存在的,你把鼠标指向button1的后面就可以看到一个长长的竖条,那个就是button2,已经非常非常小了。因此,在layout_width设置为fill_parent的时候,weight所代表的是你的控件要优先尽可能的大。
当layout_width设置为wrap_content的时候,即适应内容的宽度,意思是这个控件要尽可能的小,只要能把内容显示出来就可以了,同样的,button1的weight为1,button2的weight为2。那麼button1要优先尽可能的小,而button2也要尽可能的小,只是优先级不一样,因为设置了weight,所以这两个控件总的宽度要填满父布局的宽度,所以就又要计算每个控件所占据的大小,此时,button1的优先级较高,共有两份,一份1/3,一份2/3,button1要尽可能的小,那button1当然要选1/3,因此,我们看到的效果反而是button2占据的较大。这里要说的是如果把权值同样做如下设置:button1为1,button2为2000,那button1是不是就要占据1/2000的空间呢?这麼理解就错了,刚才说了,要尽可能的小,但这个小是有一个限度的,那就是wrap_content,就是还要是内容完完整整的显示出来,同样的,尽可能的大也是有一个限度的,那就是父布局的宽度。因此,在layout_width设置为wrap_content的时候,weight所代表的是你的控件要优先尽可能的小。
所以,要对weight做了解,要深深的理解下面两句话:
在layout_width设置为fill_parent的时候,layout_weight所代表的是你的控件要优先尽可能的大,但这个大是有限度的,即fill_parent.
在layout_width设置为wrap_content的时候,layout_weight所代表的是你的控件要优先尽可能的小,但这个小是有限度的,即wrap_content.
layout_height 同 layout_width.
类中设置权重方法:
setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, 1));