0

I have checkboxpreference in preference activity and I want that when one of the checkbox is enabled then other checkbox should get to disable and vice versa. I wants to do that from my main class activity.

Here is my code:

Preferencecheckbox.xml

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
    android:defaultValue="true"
    android:icon="@drawable/img"
    android:key="check1"
    android:title="first" />
<CheckBoxPreference
    android:defaultValue="false"
    android:icon="@drawable/img2"
    android:key="check2"
    android:title="second" />
</PreferenceScreen>

Preferenceclass.java

public class preferenceclass extends PreferenceActivity {

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferencecheckbox);
}
Ravi
  • 189
  • 1
  • 15

2 Answers2

1

You need to add a dependency to the checkbox you need disabled.

Like this:

<CheckBoxPreference
    android:defaultValue="false"
    android:icon="@drawable/img2"
    android:key="check2"
    android:title="second" 
    android:dependency="check1" />

Update To disable other preferences via code.

 final CheckBoxPreference checkbox2 = (CheakBoxPreference) findPreference("pref_checkbox2_key");

    CheckBoxPreference switch = (CheakBoxPreference) findPreference("pref_switch_key");
            switch.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(Preference preference) {
                    if (switch.isChecked()) {
                        checkbox2.setEnabled(false);
                    } else {
                        checkbox2.setEnabled(true);
                    }
                    return true;
                }
            });
    persistCheckBoxState(switch, checkbox2);

To persist the change when activity is closed, you need to get the preferences references like this and add directly below.

public void persistCheckBoxState (CheckBoxPreference switch, CheckBoxPreference checkbox2) {
if (switch.isChecked ()){ 
     checkbox2.setEnabled(false);
      } else {
      checkbox2.setEnabled(true);
    }
}
codeFreak
  • 353
  • 1
  • 3
  • 15
1

Maybe a ListPreference is more what you want. From a usability point of view this would make more sense. When you have to choose one selection out of many this would be the most obvious way to do it. See this post for further instructions

Pynnie
  • 136
  • 12
  • well listprefernce works but I am not able to use image with it – Ravi Oct 16 '17 at 14:12
  • well, that should not be a problem after all. See this post for further instructions : https://stackoverflow.com/a/6194194/6868843 – Pynnie Oct 17 '17 at 07:09