Android之UI布局
布局(Layout)的概念是针对Activity的,Activity就是布满整个Android设备的窗口或者悬浮于其他窗口上的交互界面。在一个应用程序中通常由多个Activity构成,每个需要显示的Activity都需要在AndroidManifest.xml文件之中声明。
布局方式
为了适应各种界面风格,Android提供了五种布局规范,利用这五种布局,基本上可以在设备上随心所欲的摆放任何UI组件。
- FrameLayout(帧布局)
- LinearLayout(线性布局)
- RelativeLayout(相对布局)
- TableLayout(表格布局)
- AbsoluteLayout(绝对布局)
线性布局(LinearLayout)
LinearLayout是最常用的布局方式,在XML文件中使用标记。它会将容器里的UI组件一个一个挨着排列起来。但是LinearLayout不会换行,当UI组件超出屏幕之后,则不会被显示出来。LinearLayout有两个重要的XML属性:android:gravity(对齐方式);android:orientation(排列方式)。
android:orientation(排列方式),设定了LinearLayout中包含的UI组件的排列方式,有两个选项vertical(竖向)、horizontal(横向,默认值)
android:gravity(对齐方式),设定LinearLayout中包含UI组件的对齐方式,其选项很多,常用上(top)、下(bottom)、左(left)、右(right)。
例子
<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="match_parent"
tools:context=".MainActivity" android:orientation="horizontal" android:gravity="bottom">
<Button
android:layout_weight="1"
android:text="button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:text="button2"
android:layout_gravity="top"
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:text="button3"
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
帧布局(FrameLayout)
帧布局是最简单的布局方式,所有添加到这个布局中的视图都是以层叠的方式显示,并且后声明的遮挡先声明的控件。
帧布局容器为每个加入其中的组件创建一个空白的区域(称为一帧),所有每个子组件占据一帧,这些帧都会根据gravity属性执行自动对齐。
例子
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity"