Search code examples
androidpreferences

Preferences activity deprecated


I am doing an app with preferences but I have used a method that is deprecated and it says : "This function is not relevant for a modern fragment-based PreferenceActivity". My code is this:

public class Settings extends PreferenceActivity {
/** Called when the activity is first created. */

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    addPreferencesFromResource(R.xml.preferences);
}

}

How can I update this to not deprecated function. Thank you very much.


Solution

  • The new way is to do the Preferences in an Fragment instead of an Activity. This is espacially true for large screens and tablets. Fragments can be shown separate or next to each other over an Activity according to screen size. Use them like this:

    public static class YourPreferenceFragment extends PreferenceFragment {
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            // Load the preferences from an XML resource
            addPreferencesFromResource(R.xml.preferences);
        }
    }
    

    and instead of calling the PreferenceActivity you make a call to the Fragment in your Activity:

    YourPreferenceFragment prefFragment = new YourPreferenceFragment();
    prefFragment.show(getFragmentManager(), "someFragmentId");