【问题标题】:Android Checkbox in Custom Preference not updating自定义首选项中的 Android 复选框未更新
【发布时间】:2019-03-06 03:49:02
【问题描述】:

我正在尝试实现自定义CheckBoxPreference - 如果用户点击实际复选框,它会切换状态,但如果他们点击名称,则会打开一个偏好片段。为此,我重写了OnBindView(View view) 方法,删除了view 的Click 侦听器,并尝试将OnClickListener 分别添加到它的每个子视图中。但是,绑定到 Android.Support.V7.Widget.AppCompatCheckBoxOnClickListener 不会更新复选框的可见状态,即使首选项本身已成功保存

protected override void OnBindView(View view)
{       
    base.OnBindView(view);
    view.Clickable = false;
    ViewGroup vg = (ViewGroup)view;
    for (int i = 0; i < vg.ChildCount - 1; i++)
    {
        vg.GetChildAt(i).SetOnClickListener(new DoOpenFragment(this));
    }
    vg.GetChildAt(vg.ChildCount - 1).SetOnClickListener(new DoCheckBoxClick(this)); 
}

private class DoCheckBoxClick : Java.Lang.Object, View.IOnClickListener
{
    private OpenFragmentCheckboxPreference Pref;
    public DoCheckBoxClick(OpenFragmentCheckboxPreference pref)
    {
        Pref = pref;
    }
    public void OnClick(View v)
    {
        var b0 = Pref.GetPersistedBoolean(true);
        Pref.PersistBoolean(!b0);
        var cb = ((v as ViewGroup).GetChildAt(0) as Android.Support.V7.Widget.AppCompatCheckBox);
        var b1 = Pref.GetPersistedBoolean(true);
        cb.Checked = b1;
        Pref.NotifyChanged();
        cb.Invalidate();
    }
}

如您所见,我尝试同时使用 Preference 的 NotifyChanged 方法和实际 CheckBox 小部件的 Invalidate 方法,但都不起作用。 (额外的、不必要的变量仅用于调试)。知道我可能缺少什么实际上会导致复选框被重绘并显示其正确状态的调用吗?谢谢!

【问题讨论】:

    标签: android xamarin.android android-widget android-preferences


    【解决方案1】:

    想通了 - 我应该在 OnBindView 中设置 CheckBox.Checked,而不是在 OnClick 侦听器中:

        protected override void OnBindView(View view)
        {
            base.OnBindView(view);
            view.Clickable = false;
            for (int i = 0; i < vg.ChildCount - 1; i++)
            {
                vg.GetChildAt(i).SetOnClickListener(new DoOpenFragment(this));
            }
            ((vg.GetChildAt(vg.ChildCount - 1) as ViewGroup).GetChildAt(0) as Android.Support.V7.Widget.AppCompatCheckBox).Checked = GetPersistedBoolean(true);
            vg.GetChildAt(vg.ChildCount - 1).SetOnClickListener(new DoCheckBoxClick(this));
        }
    
        private class DoCheckBoxClick : Java.Lang.Object, View.IOnClickListener
        {
            private OpenFragmentCheckboxPreference Pref;
            public DoCheckBoxClick(OpenFragmentCheckboxPreference pref)
            {
                Pref = pref;
            }
            public void OnClick(View v)
            {
                var b0 = Pref.GetPersistedBoolean(true);
                Pref.PersistBoolean(!b0);
                Pref.NotifyChanged();
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2011-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-13
      • 2011-10-05
      • 1970-01-01
      • 2012-06-17
      相关资源
      最近更新 更多