安卓的佈局有六大類,它們之間的關係如下圖:
除了TableLayout繼承LinearLayout外,全部繼承自ViewGroup類
今天主要了解LinearLayout,其中文譯名就是線性佈局是最常用的兩個佈局之一
<?xml version="1.0" encoding="utf-8"?>
<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"
android:orientation="vertical" tools:context="activityandintent.yougel.com.learnview.LearnLinearActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/app_name"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/app_name"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/app_name"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/app_name"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/app_name"/>
</LinearLayout>
界面:
LinearLayout有個重要的屬性是android:orientation,當屬性值是vertical時,垂直排布,如果是horizontal則是水平排布。
下面屬於個人理解:
線性佈局的線性並不是指佈局中部件排成一條線,而是佈局中的部件都會“佔據一條線”例如上圖是垂直進行排布,每個按鈕都“佔據一行”通過設置按鈕的android:layout_gravity的屬性讓按鈕在其所在行左中右放置
<?xml version="1.0" encoding="utf-8"?>
<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"
android:orientation="vertical" tools:context="activityandintent.yougel.com.learnview.LearnLinearActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/app_name"
android:layout_gravity="right"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/app_name"
android:layout_gravity="center"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/app_name"/>
</LinearLayout>
界面:
同理,如果是水平排布,則每個按鈕就會“佔據一列”,每個按鈕可以在所在列進行上中下的放置