Android preference multiple dependency with CheckBoxPreference

Android preference multiple dependency

Android preference multiple dependency is not out-of-the-box feature until api level 14 introduced us with SwitchPreference (extends TwoStatePreference) to implement such feature. the old CheckBoxPreference can’t do that.

 

If your app is designed for newer systems only, (min-api equal or higher than 14) that won’t be a problem for you – because you can use the new SwitchPreference element to get at least 2 states, but if your app designed to work with older api support, or more than 2 dependencies on one element – you need another method.

Note: you can always implement both ways! use the ‘/xml-v14‘ directory to create multiple version of your XML, better with include, one for API 14 with SwitchPreference, and one for the old API’s with the following solution.

android preference multiple dependency android preference multiple dependency

The solution

For one of your elements — you can set it to depend on the checkbox using the built-in dependency, but the others?.. will need to use some code to get the desired behavior.

  1. we’ll need to programmatically disable the preference we want to disable when the CheckBox status changes using listener.
  2. Another problem is on screen rotation – the PreferenceScreen is being recreated and we should disable the needed preferences at the onCreate() constructor also.

The code

Add the following code to your PreferenceActivity.

setStatus – helper tool.
chkboxListener – Listener for onclick on the checkbox to disable pref2 in our example.

And our onCreate() which sets the listener and update status from the current preferences status.

 

That’s it! good luck!

 

That’s it!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.