更博不能停,今天讲布局~~~
1、LinearLayout:
线性布局,是Android五大布局中出镜率最高的布局。我个人理解为线性布局即是给它的子控件添加一些条条框框的约束,使这些子控件能整整齐齐规规矩矩地摆放在布局中。
2、LinearLayout常用属性:
在添加一个LinearLayout时,通常会设置它的一些常用属性,这些属性是对它所包含的所有子类控件进行位置安排。
例如,
android:gravity="center_horizontal"
//gravity指的是在LinearLayout这个父类容器中的子控件的摆放方式
//常用的属性值有:
//center_vertical:垂直y轴居中
//center_horizontal:水平居中
//center:水平垂直都居中
//right:子类控件位于当前布局的右边
//left:子类控件位于当前布局的左边
//bottom:子类控件位于当前布局的下面
//也可使用“|”来同时使用gravity中的两个属性
//如android:gravity="right|bottom"表示子类控件位于当前布局的右下方
android:orientation="vertical"
//orientation表示子类控件在LinearLayout中的排列方式
//属性值分为vertical---垂直排布
//和horizontal---水平排布
3、在LinearLayout中子类控件的常用属性:
例如:
android:layout_gravity="bottom"
//这里的layout_gravity一定要和gravity时区分开,记得我刚开始学布局的
//时候对gravity和layout_gravity晕了好久,后来进行了系统的比较才终于
//分清楚。本文最后总结会给出二者的比较区别
//layout_gravity指的是子类控件在父类容器中的一个位置
//其他常用属性值同上
另一个常用属性是layout_weight
android:layout_weight="1"
这个属性讲起来有点抽象,简单的说就是当前控件占父类容器的一个比例
举个栗子:
我在LinearLayout中添加了3个Button,如下图所示
xml文件如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
tools:context=".MainActivity" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button1"/>
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button2" />
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button3" />
</LinearLayout>
可以看到LinearLayout的宽是填满屏幕,但是3个button并没有填满LinearLayout。
然后现在我在button3中添加一句android:layout_weight=”1”
效果就会变成如下:
可以看到,之前LinearLayout中剩余的空间被button3填满了,这就是因为layout_weight属性。
4、gravity与layout_gravity:
最后再来说一说这两个长得很像的属性,它们的关系应该是用父子来形容,而不是兄弟。
gravity是给父类容器用的,而layout_gravity是给子类控件用的。
举个栗子(可能不太恰当):
在一个教室里,老师规定:学生们只能坐在教室的中间,不能坐过道两边。那么就可以理解为这个老师设置了一个gravity属性来约束学生。然后这些学生里有一个比较有想法的,他选择了最靠近过道的位置,虽然被约束了,但是他可以在这个范围内选一个自己喜欢的位置呀,所以他给自己设定了一个layout_gravity。
这就是二者的区别,其实多用几次这些属性,自然就能明白其中的差别了~