有时我的RadioGroup
按钮在选择时不会被选中。我使用Xamarin.Android
,RadioButtons
中约有RadioGroup
。奇怪的是,焦点总是在单击的RadioButton上设置,但有时相同的RadioButton
在点击后未设置为Checked。以下是我目前使用的示例代码:
radioGroup.CheckedChange += delegate
{
var radioButton = FindViewById<RadioButton>(radioGroup.CheckedRadioButtonId);
radioButton.Focusable = true;
radioButton.FocusableInTouchMode = true;
radioButton.RequestFocus();
radioButton.Checked = true;
};
每次选择时,我如何将每个RadioButton标记为已选中? 提前谢谢。
答案 0 :(得分:3)
奇怪的是,焦点始终在单击的RadioButton上设置,但有时相同的RadioButton在单击后未设置为Checked。
因为当您点击RadioButton时GetFocus总是首先出现,所以当您第一次点击CheckedChange
时,RadioButton
事件永远不会被触发。
所以正确的方法是为每focusChange
注册RadioButton
事件,并在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;
}
}
}