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

Android 簡明開發教程十八:自定義對話框 Transform

編輯:Android 開發教學

Android 自帶的 AlertDialog、ProgressDialog、DatePickerDialog、TimePickerDialog 足以應付一般的對話框需求。當它們不夠用時,就得自己做一個。

三種自定義路線

第一種是把 Activity 當 Dialog 用,透過主題讓它在視覺上與對話框一致——顯示在其他 Activity 之前且背景半透明:

<Activity android:name="MyDialogActivity" android:theme="@android:style/Theme.Dialog" ></Activity>

本例採用另外兩種做法,用它來承載一組圖形變換(Transform)的選項:

Primitive: Rectangle, Ellipse, Text
Pen: Thin, Thick, Dashed
Brush: Solid, Gradient, Texture
Transform: Identity, Rotate, Scale, Shear
Rendering: Stroke, Fill, Stroke and Fill

先寫版面

在 res/layout 下新增 transformoption.xml 作為自定義對話框的版面:

<?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"
>
 <ScrollView
   android:layout_width="fill_parent"
   android:layout_height="fill_parent">
   <LinearLayout
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
     android:orientation="vertical"
    >
     <TextView
       android:text="Primitive"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content">
       </TextView>
     <RadioGroup
       android:layout_width="wrap_content"
       android:layout_height="wrap_content">
       <RadioButton
         android:text="Rectangle"
         android:id="@+id/radioRectangle"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content">
         </RadioButton>
       <RadioButton
         android:text="Ellipse"
         android:id="@+id/radioEllipse"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content">
         </RadioButton>
       <RadioButton
         android:text="Text"
         android:id="@+id/radioText"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content">
         </RadioButton>
       </RadioGroup>
       ...(Pen、Brush、Transform、Rendering 四組同構,各含三個 RadioButton) 
   </LinearLayout>
 </ScrollView>
</LinearLayout>

版面結構本身就是本例的第一個重點:外層 LinearLayout 內嵌一個 ScrollView,ScrollView 裡再放一個垂直 LinearLayout。之所以要 ScrollView,是因為五組選項疊起來的高度在小螢幕上必然溢出,少了這一層,底部的 Rendering 群組就會被永遠裁掉。

第二個重點是每一組都必須用 RadioGroup 包住 RadioButton。RadioGroup 不只是排版容器,它同時負責「同組互斥」的行為管理——這正是單選語意得以成立的實作基礎。若把 RadioButton 直接放在 LinearLayout 裡,它們會各自獨立,可以同時被勾選,就不是單選了。

第三個重點是 id 的命名。radioRectangle、radioEllipse 這種「型別加選項」的命名,讓後續在程式碼中讀取時能一眼看出所屬群組,也方便用迴圈批次處理同組的按鈕。

最後,把這個自定義版面塞進對話框的方式有兩種:一是用 Dialog 搭配 setContentView,二是用 Activity 搭配 Dialog 主題。前者輕巧、生命週期單純;後者能享受 Activity 的完整生命週期管理與 configChanges 處理。選擇哪一種,取決於你的對話框需不需要在旋轉螢幕時保留狀態。

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