为了适应各种风格,Android 提供了5种布局,分别是
LinearLayout,
TableLayout,
RelativeLayout,
AbsoluteLayout,
FrameLayout
先说第一种,LinearLayout,这种布局是最常见的布局,分为水平线性布局和垂直线性布局,通过android:orientation的属性可以设置线性布局方向。看下面这个例子。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation = "vertical" >
<TextView
android:id="@+id/textView1"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:text="@string/enqueryCenter">
</TextView>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation = "horizontal"
android:gravity = "right" >
<Button
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:text="@string/Confirm">
</Button>
<Button
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:text="@string/Cancel">
</Button>
</LinearLayout>
</LinearLayout>
看一下效果图
最外层是一个垂直线性布局,宽度是整个屏幕(fill_parent),高度是刚好适合控件(wrap_content),然后依次添加一个TextView和一个水平布局的LinearLayout,在这个布局里,android:gravity = "right",所以摆放的两个button是在右边。
android:gravity 是LinearLayout的一个很重要的布局方式,用于布局中控件的对齐方式,如果是没有子控件的控件设置了该属性,是表示其内容的对齐方式,比如TextView里内容的对齐方式。如果是有子控件的控件设置该属性,是表示子控件的对齐方式,如果是设置多个值,用|来分开。
android:gravity和android:layout_gravity的区别。
android:gravity是指这个元素里所有的子元素对于这个元素的布局,而android:layout_gravity是指这个元素相对于父元素(比如layout)的布局位置。
还有一个重要属性是android:layout_weight
这个是一个非负数属性,用来设置该控件所占比例,比如说你有两个button,分别设置成1,那么,每一个button会被拉伸成屏幕的一半,如果有3个button被设置成1,那么3个button每个占1/3, 如果是0,那么就是button的原始大小,不会被拉伸。