未在RadioGroup上检查RadioButton按钮单击Xamarin.Android

时间:2017-06-20 13:32:26

标签: c# android xamarin xamarin.android radio-button

有时我的RadioGroup按钮在选择时不会被选中。我使用Xamarin.AndroidRadioButtons中约有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标记为已选中? 提前谢谢。

1 个答案:

答案 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;
        }
    }
}