LinearLayout被称为线性布局,是一种非常常用的布局。这个布局会将它所包含的控件在线性方向上依次排列。
这里我们通过android:orientation属性指定,vertical表示垂直方向上排列,horizontal表示水平方向上排列。
这里值得注意的是,如果排列方向是前者,那么android:layout_height属性不能被指定为match_parent,否则后面的控件就没有可放置的位置了。同理,如果是后者,则android:layout_width属性不能是match_parent。
先上一个图:
然后给代码:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">
<TextView
android:text="red"
android:layout_gravity="top"
android:layout_width="80dp"
android:layout_height="80dp"
android:background="#aa0000"
android:gravity="center"/>
<TextView
android:text="green"
android:layout_gravity="center_vertical"
android:layout_width="80dp"
android:layout_height="80dp"
android:background="#00aa00"
android:gravity="center"
/>
<TextView
android:text="blue"
android:layout_gravity="bottom"
android:layout_width="80dp"
android:layout_height="80dp"
android:background="#0000aa"
android:gravity="center"
/>
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">
<Button
android:text="btn1"
android:layout_gravity="left"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:text="btn2"
android:layout_gravity="center_horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:text="btn3"
android:layout_gravity="right"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
首先介绍一下android:layout_gravity属性,它用于指定控件在布局中的对齐方式。唯一需要注意的是,布局方式是vertical时,只有在水平方向上的对齐方式才能生效,反之亦然。
而android:gravity属性是用于指定文字在控件中的对齐方式。
最后就是android:layout_weight属性,这个属性允许我们使用比例的方式来指定控件的大小,在手机屏幕的适配性上作用很大。就如上面的2个子布局,就是一比一的比例。