RadioButton
在本部分中,你将创建两个互斥单选按钮, (启用一个按钮禁用另一个) ,使用RadioGroup
和RadioButton
部件。 按下任一单选按钮时,将显示 Toast 消息。
打开 Resources/layout/Main.axml 文件,并添加两 RadioButton
个 RadioGroup
嵌套在) (中的 LinearLayout
s:
<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 署名许可中所述的术语使用。