Share via


RadioButton

在本節中,您將使用 來建立兩個互斥的單選按鈕(讓其中一個停用另一個按鈕) RadioGroupRadioButton 部件。 按下任一單選按鈕時,將會顯示快顯通知訊息。

開啟 Resources/layout/Main.axml 檔案,並新增兩RadioButton個 s,巢狀在 中 RadioGroup (內部LinearLayout):

<RadioGroup
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:orientation="vertical">
  <RadioButton android:id="@+id/radio_red"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Red" />
  <RadioButton android:id="@+id/radio_blue"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Blue" />
</RadioGroup>

請務必將 RadioButton群組在一起的 RadioGroup 元素,以便一次不選取一個以上的專案。 Android 系統會自動處理此邏輯。 當一個 RadioButton 選取群組內的所有其他人都會自動取消選取。

若要在選取每個 RadioButton 項目時執行動作,我們需要撰寫事件處理程式:

private void RadioButtonClick (object sender, EventArgs e)
{
    RadioButton rb = (RadioButton)sender;
    Toast.MakeText (this, rb.Text, ToastLength.Short).Show ();
}

首先,傳入的發件者會轉換成 RadioButton。 然後 Toast 訊息會顯示選取的單選按鈕文字。

現在,在底部 OnCreate() 方法,新增下列專案:

RadioButton radio_red = FindViewById<RadioButton>(Resource.Id.radio_red);
RadioButton radio_blue = FindViewById<RadioButton>(Resource.Id.radio_blue);

radio_red.Click += RadioButtonClick;
radio_blue.Click += RadioButtonClick;

這會從設定中擷取每個 RadioButton,並將新建立的事件處理程式新增至每個 。

執行應用程式。

提示

如果您需要自行變更狀態(例如載入已儲存 CheckBoxPreference的 時),請使用 Checked 屬性 setter 或 Toggle() 方法。

此頁面的部分是根據 Android 開放原始碼專案所建立和共用的工作進行修改,並根據 Creative Commons 2.5 屬性授權中所述的詞彙使用。