LinearLayout的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>
复制代码

       

如果两个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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值