1、线性布局
线性布局(LinearLayout)主要以水平和垂直方式来显示界面中的控件。当控件水平排列时,显示顺序依次为从左现石,当控件垂直排列时,显示顺序依次为从上到下。
在线性布局中,有一个非常重要的属性orientation,用于控制控件的排列方向,该属性有两个值vertical和horizontal (默认),其中,vertical 表示线性布局垂直显示,horizontal 表示线性布局水平显示。
【实例1】
接下来通过orientation属性,设置三个按钮垂直排列,具体代码如下所示。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="按钮1"
android:textSize="30sp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="按钮2"
android:textSize="30sp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="按钮3"
android:textSize="30sp"/>
</LinearLayout>
预览效果:
在上述代码中,将orientation属性值设置为vertical,控件垂直显示。若将该值修改为horizontal则控件会水平显示,预览效果如图所示。
从上图可以看出,当控件水平排列时,3个Button未占满行右侧留有空白区域, 这样既不美观又浪费空间。此时,利用layout weight属性可完美解决这个问题,该属性被称为权重,通过比例调整布局中所有控件的大小,在进行屏幕适配时起到关键作用,具体代码如下所示。
【实例2】
<?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="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="0"
android:layout_height