在網上看了一些對Layout_weight的講解,有些說的比較片面,只列舉了一種情況,然后自己通過實驗和一些比較好的文章總結了一下,特此記錄下來,以備以后所用。Layout_weight是線性布局,也就是LinearLayout里面用到的,下面通過實驗來看這個Layout_weight的特性。
1.當控件的屬性android:layout_width="fill_parent"時,布局文件如下:
Xml代碼
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="
http://schemas.android.com/apk/res/android
"
android:orientation="horizontal" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_weight="1"
android:text="Button1" />
<Button android: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,運行效果為:
我們看到,Button1占了2/3,Button2占了1/3。如果此時把button2的weight設置成2000,不是說Button2就消失了,而是Button1的寬度幾乎占滿了屏幕寬度,而屏幕最后一絲細條則是留給Button2的,已近非常小了,沒有顯示出來。截圖如下:
得出結論:在layout_width設置為fill_parent的時候,layout_weight代表的是你的控件要優先盡可能的大,但盡可能大是有限度的,即fill_parent.
2.當控件的屬性android:layout_width="wrap_content"時,布局文件如下:
Xml代碼
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="
http://schemas.android.com/apk/res/android
"
android:orientation="horizontal" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_weight="1"
android:text="Button1" />
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_weight="2"
android:text="Button2" />
</LinearLayout>
同樣,Button1的weight設置為1,Button2的weight設置為2,但是效果與fill_parent的效果截然相反。運行效果如下:
這時,和fill_parent正好相反,Button1的寬度占據了屏幕寬度的1/3,而Button2的寬度占據了屏幕的2/3,如果此時把Button1的weight設置為2000,按照之前理解,Button1應該小的幾乎在屏幕上看不到,但是錯了,實驗告訴我們,當Button1的weight非常小時,也要"wrap_content",也就是要保證Button1至少能夠顯示。以下是Button1設置weight為2000時的運行截圖:
我們看到,Button1已經足夠小,但是要保證他能顯示出來,因此得出結論:
在layout_width設置為wrap_content的時候,layout_weight代表的是你的控件要優先盡可能的小,但這個小是有限度的,即wrap_content.
當了解這些后,我們再設計程序時,為了能夠自適應屏幕,不想給控件一個指定的寬度和高度,就可以使用這個weight屬性來讓它按自己比例來劃分屏幕高度或者寬度了。
說了他們的主要意義,其實還有更簡單的用法,可以直接把控件寬高設為零,然后設置layout_weight,即可按屏幕比例劃分,例如一行兩個控件,一個設為2,一個設為3,即一個占寬高2/5和3/5。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
