Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 資訊

Android UI 元件系列:LinearLayout 線性版面配置

編輯:Android 資訊

LinearLayout 是一個以線性方向排列子 View 的 ViewGroup,方向可以是水平,也可以是垂直。

你可以重複巢狀使用多層 LinearLayout;不過若發現巢狀層數過多,建議改用 RelativeLayout 來取代,能讓版面結構更精簡。

1、開始建立一個名為 HelloLinearLayout 的工程。

2、打開 res/layout/main.xml 並插入以下內容。

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <LinearLayout android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1"> <TextView android:text="red" android:gravity="center_horizontal" android:background="#aa0000" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_weight="1" /> <TextView android:text="green" android:gravity="center_horizontal" android:background="#00aa00" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_weight="1" /> <TextView android:text="blue" android:gravity="center_horizontal" android:background="#0000aa" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_weight="1" /> <TextView android:text="yellow" android:gravity="center_horizontal" android:background="#aaaa00" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_weight="1" /> </LinearLayout> <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1"> <TextView android:text="row one" android:textSize="15pt" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1" /> <TextView android:text="row two" android:textSize="15pt" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1" /> <TextView android:text="row three" android:textSize="15pt" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1" /> <TextView android:text="row four" android:textSize="15pt" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1" /> </LinearLayout> </LinearLayout>

仔細檢視這個 XML:根元素 LinearLayout 定義了垂直方向,其兩個子 View 都沿垂直方向堆疊。第一個子元素是水平方向的 LinearLayout,第二個子元素則是垂直方向的 LinearLayout,而這兩個巢狀的 LinearLayout 各自又包含數個 TextView,其排列方向由父 LinearLayout 標籤所定義。

3、現在打開 HelloLinearLayout.java,確認它已在 onCreate() 方法中載入 res/layout/main.xml 版面配置檔。

 public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);

setContentView(int) 方法為 Activity 載入指定的版面配置檔,其中 R.layout.main 即對應 res/layout/main.xml。

4、執行程式,你會看到如下畫面。

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