c# - 在 Xamarin.Android 中单击 RadioGroup 按钮时未选中 RadioButton

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

有时,选择时不会检查我的 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/

相关文章:

android - 为什么我会收到 WIN DEATH : Window{45087aa8 com. gigabites.fortune/com.gigabites.fortune.BuildActivity paused=false} 错误?

Android - 通过广播 Intent 传递长数组

c# - 如果发件人是静态类或静态类中的对象,如何在 MessagingCenter.Send 中指定发件人?

android - 从 Xamarin 应用程序引用 Android 库

c# - Xamarin 中的 MVVM 绑定(bind)

c# - 有没有办法只在 dapper 中读取未提交的行?

c# - 如何在SQl Server 2005 中插入时间?

c# - 调整旋转方面的正确方法

java - 在 onDestroy() 上清空 Fragment 的变量

c# - WPF 中的实例绑定(bind)与 MVVM