在 Xamarin 中切换 RadioButton Android
Toggling a RadioButton in Xamarin Android
我有一个名为 radiobutton
的 RadioButton。我想将它用作复选框。但是一旦选中,您将无法通过单击取消选中它。所以我添加了这段代码:
radiobutton.Click += (s, e) =>
{
if (radiobutton.Checked is false)
radiobutton.Checked = true;
else
radiobutton.Checked = false;
};
但是,它不起作用。使用此代码我无法检查 RadioButton。我的代码有什么问题?
这将是您的案例的预期结果。当我们点击 RadioButton 时, Checked 的值会自动改变。所以如果你再次手动设置它会陷入死循环。
顺便说一句,RadioButton 总是用于在多个选项之间选择一个值。所以解决这个问题的最好方法是使用 CheckBox 而不是 RadioButton .
如果您确实想使用 RadioButton 的样式,您可以将 RadioButton 放在 RadioGroup 中。并调用方法 ClearCheck()
取消选中按钮。
在xml
<RadioGroup
android:id="@+id/group"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton android:id="@+id/radio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Check" />
</RadioGroup>
在Activity
bool CurrentStatus = false;
private void Radio_Click(object sender, EventArgs e)
{
RadioButton radio = FindViewById<RadioButton>(Resource.Id.radio);
bool isChecked = radio.Checked;
if (isChecked && CurrentStatus)
{
RadioGroup group = FindViewById<RadioGroup>(Resource.Id.group);
group.ClearCheck();
CurrentStatus = false;
}
else
{
CurrentStatus = isChecked;
}
}
我有一个名为 radiobutton
的 RadioButton。我想将它用作复选框。但是一旦选中,您将无法通过单击取消选中它。所以我添加了这段代码:
radiobutton.Click += (s, e) =>
{
if (radiobutton.Checked is false)
radiobutton.Checked = true;
else
radiobutton.Checked = false;
};
但是,它不起作用。使用此代码我无法检查 RadioButton。我的代码有什么问题?
这将是您的案例的预期结果。当我们点击 RadioButton 时, Checked 的值会自动改变。所以如果你再次手动设置它会陷入死循环。
顺便说一句,RadioButton 总是用于在多个选项之间选择一个值。所以解决这个问题的最好方法是使用 CheckBox 而不是 RadioButton .
如果您确实想使用 RadioButton 的样式,您可以将 RadioButton 放在 RadioGroup 中。并调用方法 ClearCheck()
取消选中按钮。
在xml
<RadioGroup
android:id="@+id/group"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton android:id="@+id/radio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Check" />
</RadioGroup>
在Activity
bool CurrentStatus = false;
private void Radio_Click(object sender, EventArgs e)
{
RadioButton radio = FindViewById<RadioButton>(Resource.Id.radio);
bool isChecked = radio.Checked;
if (isChecked && CurrentStatus)
{
RadioGroup group = FindViewById<RadioGroup>(Resource.Id.group);
group.ClearCheck();
CurrentStatus = false;
}
else
{
CurrentStatus = isChecked;
}
}