为了适应不同界面的风格,android为开发人员提供了5种常用布局,分别是LinearLayout(线性布局)、RelativeLayout(相对布局)、FrameLayout(帧布局)、TableLayout(表格布局)/AbsoluteLayout(绝对布局)。
1.LinearLayout(线性布局)
首先我们来介绍线性布局,线性布局是在实际开发中比较常用的,他主要以水平和垂直的方式来显示界面中的控件。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
>
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="A"
/>
<Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="B"
/>
<Button
android:id="@+id/btn3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="C"
/>
</LinearLayout>
首先是layout_width和layout_height这两个控件属性,这两个值可以设置为wrap_content(控件大小由控件内容大小变化而变化)和match_parent(填满父窗体由父容器决定控件大小),也可以自定义大小。
改变btn3的layout_width的值使他变成match_parent:
改变三个按钮的layout_width的值,自定义为100dp、200dp、300dp:
同理layout_height也是可以一样根据自己的需求自己定义自己需要的高度大小。
之后是orientation一个关键的属性,用于控制控件的排列方向,它有两个值 vertical表示线性布局垂直显示,horizontal表示线性布局水平显示。
将orientation的值变为vertical就会变成水平显示:
你也可以根据需要使用嵌套线性布局即在线性布局中再使用线性布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
>
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="A"
/>
<LinearLayout
android:layout_width=