android 布局權重問題(最近布局經常坑爹)


 

android 布局 權重

With layout_weight you can specify a size ratio between multiple views. E.g. you have a MapView and a table which should show some additional information to the map. The map should use 3/4 of the screen and table should use 1/4 of the screen. Then you will set the layout_weight of the map to 3 and the layout_weight of the table to 1.

To get it work you also have to set the height or width (depending on your orientation) to 0px.

 

 

//權重和父容器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屬性來讓它按自己比例來划分屏幕高度或者寬度了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM