Android官方文檔—User Interface(Input Controls)(Radio Buttons)

單選按鈕

單選按鈕允許用戶從一組中選擇一個選項。如果您認爲用戶需要並排查看所有可用選項,則應使用單選按鈕的單選按鈕。如果沒有必要並排顯示所有選項,請使用微調器。

要創建每個單選按鈕選項,請在佈局中創建RadioButton。但是,由於單選按鈕是互斥的,因此必須將它們組合在一個RadioGroup中。通過將它們組合在一起,系統確保一次只能選擇一個單選按鈕。

響應Click事件


當用戶選擇一個單選按鈕時,相應的RadioButton對象接收點擊事件。

要爲按鈕定義click事件處理程序,請將android:onClick屬性添加到XML佈局中的<RadioButton>元素。此屬性的值必須是您要響應click事件時要調用的方法的名稱。然後,託管佈局的Activity必須實現相應的方法。

例如,這裏有幾個RadioButton對象:

<?xml version="1.0" encoding="utf-8"?>
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <RadioButton android:id="@+id/radio_pirates"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/pirates"
        android:onClick="onRadioButtonClicked"/>
    <RadioButton android:id="@+id/radio_ninjas"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/ninjas"
        android:onClick="onRadioButtonClicked"/>
</RadioGroup>

注意:RadioGroup是LinearLayout的子類,默認情況下具有垂直方向。

在承載此佈局的Activity中,以下方法處理兩個單選按鈕的click事件:

public void onRadioButtonClicked(View view) {
    // Is the button now checked?
    boolean checked = ((RadioButton) view).isChecked();

    // Check which radio button was clicked
    switch(view.getId()) {
        case R.id.radio_pirates:
            if (checked)
                // Pirates are the best
            break;
        case R.id.radio_ninjas:
            if (checked)
                // Ninjas rule
            break;
    }
}

您在android:onClick屬性中聲明的方法必須具有完全如上所示的簽名。具體來說,該方法必須:

  • 公開的
  • 返回viod
  • 將View定義爲唯一參數(這將是單擊的View)

提示:如果您需要自己更改單選按鈕狀態(例如加載已保存的CheckBoxPreference時),請使用setChecked(boolean)或toggle()方法。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章