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

Android 單選鈕 RadioButton 與 RadioGroup 搭配使用教學

編輯:Android 開發實例

先前介紹過可多選的 CheckBox,這次要說的是它的相對概念:只能單選的 RadioButton。單選鈕通常不單獨使用,而必須與分組元件 RadioGroup 搭配——RadioGroup 負責讓同一組內的選項互斥,選了 A 就自動取消 B。

版面宣告

<RadioGroup android:id="@+id/fengflyGroup"
    android:layout_width="fill_parent" android:layout_height="fill_parent"
    android:checkedButton="@+id/fengfly3" android:orientation="horizontal"
    android:gravity="center_vertical|center_horizontal">
    <RadioButton android:text="rad1" android:id="@+id/fengfly1"
        android:layout_width="wrap_content" android:layout_height="wrap_content"></RadioButton>
    <RadioButton android:text="rad2" android:id="@+id/fengfly2"
        android:layout_width="wrap_content" android:layout_height="wrap_content"></RadioButton>
    <RadioButton android:text="rad3" android:id="@+id/fengfly3"
        android:layout_width="wrap_content" android:layout_height="wrap_content"></RadioButton>
</RadioGroup>

android:checkedButton 用來指定預設被勾選的那一項。

事件處理:監聽群組而非個別選項

這裡與 CheckBox 最大的不同——單選鈕只要對父層的 RadioGroup 掛監聽即可,不必逐一處理:

RadioGroup group = (RadioGroup) this.findViewById(R.id.fengflyGroup);
// 響應單選鈕組內選中項變化的時間
group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        // doing actions
    }
});

回呼中的 checkedId 就是被選中項的資源 id,若全部取消則為 -1,據此即可決定後續行為。

實務提醒

要把選項排版成網格狀時,RadioGroup 不支援 wrap 排列,實務上會改用多個橫向 LinearLayout 巢狀堆疊。另外若只需要「二選一」的開關語意,Switch 或 ToggleButton 會比單選鈕更合適;而動態增減選項時,RadioGroup 的 addView() 需自行處理 index 與 id 的維護,較為麻煩。

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