When I attempt to follow Android's Developer guides and tutorials for creating a Settings Activity using Preferences, I receive warnings such as:
"The method addPreferencesFromResource(int) from the type PreferenceActivity is deprecated"
for both of these lines in the code:
getPreferenceManager().setSharedPreferencesName(PREFS_NAME);
addPreferencesFromResource(R.xml.default_values);
I know these are just warnings, but I was wondering if they will cause any issues, now or in the future, when I am running the application that I am designing.
public class DefaultValues extends PreferenceActivity {
static final String PREFS_NAME = "defaults";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getPrefs(this);
getPreferenceManager().setSharedPreferencesName(PREFS_NAME);
addPreferencesFromResource(R.xml.default_values);
}
static SharedPreferences getPrefs(Context context) {
PreferenceManager.setDefaultValues(context, PREFS_NAME, MODE_PRIVATE,
R.xml.default_values, false);
return context.getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
}
}
As the method is deprecated, it is recommended that you don't use it in your code, as it is entirely possible that it can be removed in future versions of Android. However, I am yet to come across a deprecated method that has actually been removed from Android.
No alternative method is provided in the method's description because the preferred approach (as of API level 11) is to instantiate PreferenceFragment objects to load your preferences from a resource file. See the sample code here: PreferenceActivity
Raghav Sood is correct. But if you need PreferenceFragment bad (I needed in tab) you can use this. But it can brake in the future so better to use this only for old apis. It's a little modified PreferenceFragment I made with SupportLibrary and reflection.
The preferred implementation now uses
Fragment
s. The following will work:If you face a deprecation warning from a method like this :
You have to use PreferenceFragment because API 11 and above requires such a method.
Here is an example of how to use PreferenceFragment :
1.Create /res/xml/preferences.xml to define our preferences.
2.Create PrefsFragment.java extends PreferenceFragment to addPreferencesFromResource.
3.Create SetPreferenceActivity.java to load PrefsFragment.
4.Modify the main layout, /res/layout/activity_main.xml, to show the preference.
5.The main activity, MainActivity.java.
5.Finally, modify AndroidManifest.xml to add SetPreferenceActivity.
PreferenceActivity()
is deprecated, butPreferenceFragment()
is now as well.PreferenceFragmentCompat()
is now the way to go:Add dependency
Or in case you are still using the support library:
Extend PreferenceFragmentCompat
Show your Fragment
Specify preferenceTheme
In your AppTheme, add either of the following preference themes, depending of which one you think looks better: