Search code examples
androidsharedpreferencesandroid-preferences

Disable Preference based on Value of its Dependency (Code Check)


I am attempting to do something I'm unsure of, and need someone to provide feedback.

I have 2 preferences. One of them, I want dependent on the other one's value.

Example: My "Notification Mode" Preference has 2 options: "Timer", and "Reminder"

If the User chooses the "Timer" option, I want my other Preference available to set time.

Otherwise, I want the Preference for setting the Timer to be disabled.

Here's what I've come up with inside my pref changed listener:

if (key.equals(PREF_NOTIFICATION_MODE)) {

    Preference notifModePref = findPreference(key);
    notifModePref.setSummary(sharedPreferences.getString(key, ""));

    if(!notifModePref.equals("Timer Mode")) {

        Preference timerDurationPref = findPreference(PREF_TIMER_DURATION);
        timerDurationPref.onDependencyChanged(notifModePref, true);

    } else if(notifModePref.equals("Timer Mode")) {

        Preference timerDurationPref = findPreference(PREF_TIMER_DURATION);
        timerDurationPref.onDependencyChanged(notifModePref, false);
    }
}

I'm not sure if I'm doing this correctly, or if onDependencyChanged is proper.


Solution

  • I accomplished the Goal inside of if(key.equals) by referencing the Preference in question and using if statements and a combination of using onDependencyChanged(), and setting .isEnabled(boolean) as required.