Dr. Yatish Bathla
Dr. Yatish Bathla

Reputation: 522

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?

Upvotes: 0

Views: 1264

Answers (2)

Nikola Despotoski
Nikola Despotoski

Reputation: 50538

Alternatively you can inherit CheckBoxPreference to create custom preference:

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" />

Upvotes: 0

Samuel Rabinowitz
Samuel Rabinowitz

Reputation: 135

The solution is simple: disable clicks in the java code (not XML). Do the following somewhere in your onCreate(), onStart(), onResume(), or where ever you set up your preference layout:

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.

Upvotes: 2

Related Questions