android 佈局文件的權重問題

【聲明】此文轉載自:http://m.blog.csdn.net/blog/a7a9a68/7754544

——尊重作者,知識無價,交流無限!

權重和父容器orientation有關

horizontal 指水平方向權重  android:layout_width

vertical  指垂直方向權重   android:layout_height

 

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屬性來讓它按自己比例來劃分屏幕高度或者寬度了!轉載請註明出處!

☆☆☆☆轉載請註明出處☞指尖飛落的博客

發佈了22 篇原創文章 · 獲贊 10 · 訪問量 18萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章