我要一直往前走

android的点点滴滴。

android中布局文件中 layout_weight 的属性详解

在不同的情况下,layout_weight属性作用是不同的。主要有两种属性:

 

1.当布局中的控件的尺寸(宽和高)都有指定时,它所表示的该控件在父容器中的比重,及它在父容器中所占的比例,数值越大,比重越小。

上代码:

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:id="@+id/fragment2"
 4     android:layout_width="match_parent"
 5     android:layout_height="match_parent"
 6     android:gravity="center"
 7     android:orientation="vertical">
 8 
 9     <TextView
10         android:layout_width="match_parent"
11         android:layout_height="match_parent"
12         android:layout_weight="1"
13         android:text="Hello"
14         android:textSize="30sp" />
15 
16     <Button
17         android:background="#ffbe2e15"
18         android:textColor="#ff2e140a"
19         android:id="@+id/bt"
20         android:layout_width="match_parent"
21         android:layout_height="match_parent"
22         android:layout_marginTop="20dp"
23         android:layout_weight="5"
24         android:text="点击我给你钱"
25         android:textSize="24sp" />
26 
27 </LinearLayout>

效果图:

 

 

2.当控件的宽或高不指定尺寸时,即其中一个设置为零时,layout_weight的属性表示/作用的是显示的先后顺序,数值越大顺序越靠后;

上代码:

把上面的代码中Button的高改为0dp,即可

<Button
        android:background="#ffbe2e15"
        android:textColor="#ff2e140a"
        android:id="@+id/bt"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginTop="20dp"
        android:layout_weight="5"
        android:text="点击我给你钱"
        android:textSize="24sp" />

  效果如下,我们发现Button不见了,这是因为Button中的layout_weight的属性值为5dp,大于TextView中的1dp。

他被TextView覆盖掉了,即它所显示的顺序级别必Butoon的低。

 

同理如果把TextView中layout_weight的值改为比Tutton中的大的话,比如10,那么效果将是TextView被覆盖掉了。读者可以试一下效果。

 

posted on 2015-11-03 16:10  !5  阅读(914)  评论(0编辑  收藏  举报

导航