有时,选择时不会检查我的 RadioGroup
按钮。我正在使用 Xamarin.Android
,并且 RadioGroup
中有大约 15 个 RadioButtons
。奇怪的是,焦点始终设置在单击的 RadioButton 上,但有时相同的 RadioButton
在单击后并未设置为“选中”。这是我当前使用的示例代码:
radioGroup.CheckedChange += delegate
{
var radioButton = FindViewById<RadioButton>(radioGroup.CheckedRadioButtonId);
radioButton.Focusable = true;
radioButton.FocusableInTouchMode = true;
radioButton.RequestFocus();
radioButton.Checked = true;
};
每次选择每个单选按钮时,如何将其标记为“已选中”? 提前致谢。
最佳答案
What is strange is that the focus is always set on the RadioButton clicked, but sometimes the same RadioButton is not set as Checked after click.
因为当您单击 RadioButton 时,GetFocus 总是先出现,因此当您第一次单击 RadioButton
时,CheckedChange
事件永远不会被触发。
因此,正确的方法是为每个 RadioButton
注册 focusChange
事件,并将单选按钮设置为在 focusChange
中选中事件处理程序:
public class MainActivity : Activity
{
RadioGroup radioGroup;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
radioGroup = FindViewById<RadioGroup>(Resource.Id.mGroup);
//register focus change event for every sub radio button.
for (int i = 0; i < radioGroup.ChildCount; i++)
{
var child=radioGroup.GetChildAt(i);
if (child is RadioButton)
{
((RadioButton)child).FocusChange += RadioButton_FocusChange;
}
}
}
private void RadioButton_FocusChange(object sender, Android.Views.View.FocusChangeEventArgs e)
{
//check if the radio button is the button that getting focus
if (e.HasFocus){
((RadioButton)sender).Checked = true;
}
}
}
关于c# - 在 Xamarin.Android 中单击 RadioGroup 按钮时未选中 RadioButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44654520/