简体   繁体   English

如何永久检查复选框android

[英]how to permanently checked checkbox android

I have following code: 我有以下代码:

 <CheckBoxPreference
        android:defaultValue="true"
        android:key="@key/pref_airship"
        android:persistent="true"
        android:title="@string/pref_airship" />

According to this code, Checkbox is checked when application started first time. 根据此代码,应用程序首次启动时将选中复选框。 But i want that checkbox is permanently checked and user can't uncheck this checkbox(for example it changes it color and remain always checked). 但是我希望该复选框被永久选中,并且用户不能取消选中该复选框(例如,它更改颜色并始终保持选中状态)。 Any suggestion how to do this? 任何建议如何做到这一点?

The solution is simple: disable clicks in the java code (not XML). 解决方案很简单:禁用Java代码(而不是XML)中的单击。 Do the following somewhere in your onCreate(), onStart(), onResume(), or where ever you set up your preference layout: 在您的onCreate(),onStart(),onResume()或您设置首选项布局的任何地方执行以下操作:

CheckBoxPreference airshipPref = (CheckBoxPreference) findPreference("pref_airship");
airshipPref.setEnabled(false);

That way, it will not handle clicks and it should not listen to user input, thereby remaining always checked. 这样,它将不会处理点击,也不会监听用户输入,因此始终处于选中状态。

Alternatively you can inherit CheckBoxPreference to create custom preference: 或者,您可以继承CheckBoxPreference来创建自定义首选项:

public class DisabledCheckBoxPreference extends CheckBoxPreference{

        public DisabledCheckBoxPreference(Context context, AttributeSet attrs,
                int defStyle) {
            super(context, attrs, defStyle);
            // TODO Auto-generated constructor stub
        }

        public DisabledCheckBoxPreference(Context context, AttributeSet attrs) {
            super(context, attrs);
            // TODO Auto-generated constructor stub
        }

        public DisabledCheckBoxPreference(Context context) {
            super(context);
            // TODO Auto-generated constructor stub
        }

        @Override
        protected void onBindView(View view) {
            view.setEnabled(false);
            super.onBindView(view);
        }

    }

Usage: 用法:

<com.your.package.name.DisabledCheckBoxPreference
        android:defaultValue="true"
        android:key="@key/pref_airship"
        android:persistent="true"
        android:title="@string/pref_airship" />

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

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