RadioButton

在本部分中,你将使用下列项创建两个互斥的单选按钮(启用一个会禁用另一个):RadioGroupRadioButton 小组件。 按下任一单选按钮时,都将显示一条 Toast 消息。

打开 Resources/layout/Main.axml 文件并添加两个嵌入在 RadioGroup(位于 LinearLayout 中)中的 RadioButton

<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>

必须通过 RadioGroup 元素将 RadioButton 放在同一个组中,以便一次只能选择其中的一个。 此逻辑由 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 属性资源库或 Toggle() 方法。

本页的部分内容是根据 Android 开源项目创建和共享的工作进行的修改,并根据 Creative Commons 2.5 Attribution License 中的条款进行使用。