Preferences without deprecated methods

2019-01-19 16:48发布

问题:

I'm trying to (correctly) implement a preferences screen, but the problem is that all the methods used to read preferences from xml files are deprecated (or I just don't recognize them). The official sample code on the dev site (PreferenceActivity) uses deprecated methods. Has anyone found out a way to implement a preferences screen with an xml file but without using either: addPreferencesFromResource(int) or findPreference(CharSequence)? Or have the methods just been marked deprecated without implementing the alternative yet?

EDIT: Developing for Android version 2.1

回答1:

Why its deprecated and what is the alternative is pretty well explained in documentation:

This is the base class for an activity to show a hierarchy of preferences to the user. Prior to HONEYCOMB this class only allowed the display of a single set of preference; this functionality should now be found in the new PreferenceFragment class. If you are using PreferenceActivity in its old mode, the documentation there applies to the deprecated APIs here.

In other words, if you want to be HONEYCOMB compliant, then you should use PreferenceFragment for your PreferenceActivity. A detailed explanation on how to use fragments can be found in dev guide.



回答2:

In Android 3, API Level 11, the fragment-based preference model was introduced, thus deprecating methods that "is not relevant for a modern fragment-based PreferenceActivity."

Since the online reference is the latest version, it shows the methods as deprecated. By manipulating the API Level dropdown, you can mark the methods that are not in the given Android version, but it doesn't update the descriptions to match, which is why it still shows up as deprecated.

If you don't plan on supporting Android 3+ you should just use the old methods, as the fragment-based solutions will not work to versions prior to this.