Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android LinearLayout 常用布局實戰:垂直與嵌套對齊

編輯:關於 Android 開發

用 LinearLayout 實現常用的對齊布局

下面要實現的是一種頗為常用的布局效果:外層垂直排列,內部通過嵌套 LinearLayout 和 gravity 屬性,實現按鈕的左對齊、右對齊、居中以及底部對齊等多種排列方式。具體的 XML 代碼如下:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<!-- 第一行:左側一個按鈕,右側一個按鈕 -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_weight="1" >

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:gravity="right">

<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />

</LinearLayout>
</LinearLayout>

<!-- 第二行:居中 -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_weight="1">

<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />

</LinearLayout>

<!-- 第三行:底部,內含左右兩個按鈕 -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="bottom"
>

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>

<Button android:id="@+id/button4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" />

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:gravity="right" >

<Button
android:id="@+id/button5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />

</LinearLayout>

</LinearLayout>

</LinearLayout>

</LinearLayout>

這個例子很好地說明了 LinearLayout 的兩個核心屬性:orientation 決定子元素是水平還是垂直排列,gravity 決定子元素在容器中的對齊方式;而 layout_weight 則用於按比例分配剩餘空間。通過靈活嵌套,就能輕鬆拼出各種常見的界面布局。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved