简体   繁体   English

Xamarin.Android中未选中RadioGroup按钮上的RadioButton

[英]RadioButton not checked on RadioGroup button click in Xamarin.Android

Sometimes my RadioGroup buttons are not checked while selecting. 有时选择时未选中我的RadioGroup按钮。 I am using Xamarin.Android and I have about 15 RadioButtons in RadioGroup . 我正在使用Xamarin.Android并且在RadioGroup有大约15个RadioButtons 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上,但有时在单击后未将同一RadioButton设置为Checked。 Here is the sample code I currently use: 这是我当前使用的示例代码:

radioGroup.CheckedChange += delegate
{
    var radioButton = FindViewById<RadioButton>(radioGroup.CheckedRadioButtonId);
    radioButton.Focusable = true;
    radioButton.FocusableInTouchMode = true;
    radioButton.RequestFocus();
    radioButton.Checked = true;
};

What can I do to mark each RadioButton as Checked everytime I select it? 每次选择时,如何将每个RadioButton标记为已选中? Thanks in advance. 提前致谢。

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上,但有时在单击后未将同一RadioButton设置为Checked。

Because GetFocus always comes first when you click on the RadioButton, thus the CheckedChange event never got triggered when you click on the RadioButton for the first time. 因为当您单击RadioButton时GetFocus始终排在第一位,所以当您第一次单击RadioButton时就不会触发CheckedChange事件。

So the correct way to do that is to register the focusChange event for every RadioButton and set the radio button to checked in the focusChange event handler: 因此,正确的方法是为每个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;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM