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

Android RadioButton 單選框的使用方法詳解

編輯:關於 Android 程式設計

RadioButton(單選框)與 RadioGroup(單選群組)的搭配,能實現「一組之中只能選一個」的互動效果,最典型的應用就是性別選擇。本文示範如何透過監聽 RadioGroup 的狀態變化來回應使用者的選擇。

Activity 中的實作

關鍵在於為 RadioGroup 註冊 setOnCheckedChangeListener,在回呼中透過 checkedId 判斷被選中的是哪個單選鈕:

public class MainActivity extends Activity {
    public RadioGroup mRadioGroup1;
    public RadioButton mRadio1, mRadio2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mRadioGroup1 = (RadioGroup) findViewById(R.id.gendergroup);
        mRadio1 = (RadioButton) findViewById(R.id.girl);
        mRadio2 = (RadioButton) findViewById(R.id.boy);
        mRadioGroup1.setOnCheckedChangeListener(radiogpchange);
    }
    private RadioGroup.OnCheckedChangeListener radiogpchange = new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            if (checkedId == mRadio1.getId()) {
                Toast.makeText(getApplicationContext(), "女孩", 1).show();
            } else if (checkedId == mRadio2.getId()) {
                Toast.makeText(getApplicationContext(), "男孩", 1).show();
            }
        }
    };
}

對應的佈局檔

RadioButton 的運作方式類似 C# 中的 Radio 控制項:將多個 RadioButton 包在同一個 RadioGroup 中,該群組內的項目便只能單選。因此監聽器要掛在 RadioGroup 上,而非個別的 RadioButton:

<RadioGroup
    android:id="@+id/gendergroup"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >
    <RadioButton
        android:id="@+id/girl"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/girl" />
    <RadioButton
        android:id="@+id/boy"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/boy" />
</RadioGroup>

只要牢記「監聽器掛在 RadioGroup、透過 checkedId 判斷選項」這兩個要點,單選互動便能輕鬆搞定。

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