Search code examples
androidsharedpreferencespreferenceactivity

Enable Android Preference Item programmatically in Java


I have got the following Problem: I have to set a Preference Enabled if some environment is given. So I have written the following Code in the PreferenceActivity in the onPostCreate function:

if (myVariable == null){
     findPreference("myPref").setEnabled(true);
}

Normally this Preference is set disabled in the XML.

Now, since findPreference is deprecated, I want to know how to solve this a better way.


Solution

  • This method is deprecated, because it is irrelevant to a fragment-based activity:

    This method was deprecated in API level 11.

    This function is not relevant for a modern fragment-based PreferenceActivity.

    However, if you decide to build your PreferenceActivity without fragments, it is perfectly fine for you to use this method (You have to use it, to be honest). If you do want to use fragments, read more about them in PreferenceActivitys here.