Android 布局學習之——LinearLayout的layout_weight屬性


     一直對layout_weight屬性感到比較困惑,今天學習一下,來深入了解layout_weight屬性和它的用法。

  •      定義

    首先,看看Android官方文檔是怎么說的,畢竟人家才是權威嘛。

    

    

    官方文檔的意思是:

                 layout_weight屬性用於分配LinearLayout中的的額外空間(extra space)。

                 如果View不想拉伸的話,layout_weight值設置為0。否則的話這些像素會按比例分配到

                 這些weight值大於0的所有View。

    換句話說,也就是android:layout_weight屬性告知LinearLayout如何進行子組件的布置安排。

  •  例子

    說這么多,不如用幾個例子來形象的描述它:

   1.首先設置一個Linear_Layout布局,方向設置為水平,放置兩個TextView,不設置Layout_weight值。可以看到

   空余的白色部分就是官方文檔中所說的extra space(額外空間)。

        

  布局文件代碼:

  

 1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 2     xmlns:tools="http://schemas.android.com/tools"
 3     android:layout_width="match_parent"
 4     android:layout_height="wrap_content"
 5     android:orientation="horizontal" >
 6 
 7     <TextView
 8         android:layout_width="wrap_content"
 9         android:layout_height="wrap_content"
10         android:background="#f00"
11         android:text="TextView1" />
12     <TextView 
13         android:layout_width="wrap_content"
14         android:layout_height="wrap_content"
15         android:background="#0f0"
16         android:text="ThisIsTextView2"
17         />
18 </LinearLayout>

 

    2.設置兩個TextView的Layout_weight的值都為1。

     在上面的xml文件中,給每個TextView增加一個"android:layout_weight=1"屬性。

      

  TextView1,TextView2的layout_weight值分別設置為2和1,1和2,看運行的效果:

  2和1:

       

  1和2:

       

       相信通過以上例子和圖片,大家應該對layout_weight屬性的用法已經非常理解了。

      那么,問題又來了。如果我想要將兩個子組件分配相同的寬度或高度,那該怎么設置layout_weight呢?

      只需要將各子組件的layout_width值設置為0,這樣就避開了第一步的空間分配。

      這樣LinearLayout就只會考慮使用layout_weight值來完成空間的分配了。

     

 1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 2     xmlns:tools="http://schemas.android.com/tools"
 3     android:layout_width="match_parent"
 4     android:layout_height="wrap_content"
 5     android:orientation="horizontal" >
 6 
 7     <TextView
 8         android:layout_width="0dp"<!--將layout_width值設置為0dp以避開第一步的空間分配-->
 9         android:layout_height="wrap_content"
10         android:background="#f00"
11         android:layout_weight="1"<!--LinearLayout將會按此值分配空間-->
12         android:text="TextView1" />
13     <TextView 
14         android:layout_width="0dp"
15         android:layout_height="wrap_content"
16         android:background="#0f0"
17         android:layout_weight="1"
18         android:text="ThisIsTextView2"
19         />
20 </LinearLayout>

      

      希望這篇文章對大家有所幫助,如果喜歡,請推薦,謝謝~

      如果轉載,請在文章開頭處注明本博客地址:http:www.cnblogs.com/JohnTsai

      歡迎討論交流,郵箱:JohnTsai.Work@gmail.com


免責聲明!

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



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