Android 布局学习之——LinearLayout的layout_weight属性

     一直对layout_weight属性感到比较困惑,今天学习一下,来深刻了解layout_weight属性和它的用法。android

  •      定义

    首先,看看Android官方文档是怎么说的,毕竟人家才是权威嘛。布局

    

    

    官方文档的意思是:学习

                 layout_weight属性用于分配LinearLayout中的的额外空间(extra space)。spa

                 若是View不想拉伸的话,layout_weight值设置为0。不然的话这些像素会按比例分配到
code

                 这些weight值大于0的全部View。xml

    换句话说,也就是android:layout_weight属性告知LinearLayout如何进行子组件的布置安排。blog

  •  例子

    说这么多,不如用几个例子来形象的描述它:图片

   1.首先设置一个Linear_Layout布局,方向设置为水平,放置两个TextView,不设置Layout_weight值。能够看到文档

   空余的白色部分就是官方文档中所说的extra space(额外空间)。get

        

  布局文件代码:

  

 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

相关文章
相关标签/搜索