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

Android UI 控制項總覽:13 種常用元件與建立方式

編輯:進階開發

使用者介面就是使用者看得到、點得到的一切。前面章節談的是這些元件在 Activity 中如何被定位與排列,本章則把焦點放在元件本身。

兩個概念要先分清:View 是會在螢幕上畫出東西、使用者能與之互動的物件;ViewGroup 則是裝著其他 View 的容器,同時負責定義介面的排列方式。

View 可以寫在 XML 檔裡,這種寫法類似 HTML 的結構化描述,人類讀起來清楚明瞭。以下就是一個最直白的例子:一個垂直配置,裡頭放著一個 TextView 與一個 Button。

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="I am a TextView" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="I am a Button" /> </LinearLayout>

Android 提供的 UI 控制項

Android 內建了一批 UI 控制項,讓你不必從零打造,就能組出功能完整的圖形介面:

控制項說明
TextView最基礎的文字顯示元件。
EditTextTextView 的預定義子類別,內建豐富的文字編輯能力。
AutoCompleteTextView外觀近似 EditText,但使用者輸入時會跳出自動補全建議清單。
Button可按下或點擊以觸發動作的按鈕。
ImageButton以圖片呈現的按鈕。
CheckBox可切換開/關的核取方塊,適合呈現一組彼此不互斥的選項。
ToggleButton帶指示燈的開/關按鈕。
RadioButton單選按鈕,有選取與取消選取兩種狀態。
RadioGroup用來把一個或多個單選按鈕組織成互斥的群組。
ProgressBar為背景執行的日常任務提供視覺進度回饋。
Spinner下拉式清單,讓使用者從一組值中挑選一個,概念等同 HTML 的 select。
TimePicker讓使用者以 24 小時制或 AM/PM 制挑選時間。
DatePicker讓使用者挑選日期。

建立 UI 控制項

如前面章節所述,每個 View 都可以配上一個在整棵檢視樹中唯一的 ID。在 XML 標籤裡的寫法是:

 android:id="@+id/text_id"

要建立一個控制項,先在布局檔中定義它並指定唯一 ID:

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:id="@+id/text_id" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="I am a TextView" /> </LinearLayout>

最後在程式碼中取得它的實例,就能開始操作:

 TextView myText = (TextView) findViewById(R.id.text_id);

這個「XML 定義外觀、程式碼取得實例」的分工,是 Android UI 開發最核心的模式。把布局交給 XML、把行為交給 Java,兩邊各自獨立演進,介面調整時不必動到邏輯,邏輯修改時也不必翻修布局——這也是為什麼 Android 能把 UI 描述得如此接近網頁的結構化寫法。

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