LinearLayout的layout_weight属性

来源:互联网 发布:淘宝网店运营公司 编辑:程序博客网 时间:2024/06/05 07:20
  •    定义

    首先,看看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>
复制代码

       

如果两个view的宽度都是match_parent,那么结论如下:

设屏幕宽度为L,在两个view的宽度都为match_parent的情况下,原有宽度为L,两个的View的宽度都为L,那么剩余宽度为L-(L+L) = -L, 左边的View占比三分之一,所以总宽度是L+(-L)*1/3 = (2/3)L, 另一个就是(1/3)L

0 0