FileDocCategorySizeDatePackage
PreferenceFragment.javaAPI DocAndroid 5.1 API14538Thu Mar 12 22:22:10 GMT 2015android.preference

PreferenceFragment

public abstract class PreferenceFragment extends android.app.Fragment implements PreferenceManager.OnPreferenceTreeClickListener
Shows a hierarchy of {@link Preference} objects as lists. These preferences will automatically save to {@link SharedPreferences} as the user interacts with them. To retrieve an instance of {@link SharedPreferences} that the preference hierarchy in this fragment will use, call {@link PreferenceManager#getDefaultSharedPreferences(android.content.Context)} with a context in the same package as this fragment.

Furthermore, the preferences shown will follow the visual style of system preferences. It is easy to create a hierarchy of preferences (that can be shown on multiple screens) via XML. For these reasons, it is recommended to use this fragment (as a superclass) to deal with preferences in applications.

A {@link PreferenceScreen} object should be at the top of the preference hierarchy. Furthermore, subsequent {@link PreferenceScreen} in the hierarchy denote a screen break--that is the preferences contained within subsequent {@link PreferenceScreen} should be shown on another screen. The preference framework handles showing these other screens from the preference hierarchy.

The preference hierarchy can be formed in multiple ways:

  • From an XML file specifying the hierarchy
  • From different {@link Activity Activities} that each specify its own preferences in an XML file via {@link Activity} meta-data
  • From an object hierarchy rooted with {@link PreferenceScreen}

    To inflate from XML, use the {@link #addPreferencesFromResource(int)}. The root element should be a {@link PreferenceScreen}. Subsequent elements can point to actual {@link Preference} subclasses. As mentioned above, subsequent {@link PreferenceScreen} in the hierarchy will result in the screen break.

    To specify an {@link Intent} to query {@link Activity Activities} that each have preferences, use {@link #addPreferencesFromIntent}. Each {@link Activity} can specify meta-data in the manifest (via the key {@link PreferenceManager#METADATA_KEY_PREFERENCES}) that points to an XML resource. These XML resources will be inflated into a single preference hierarchy and shown by this fragment.

    To specify an object hierarchy rooted with {@link PreferenceScreen}, use {@link #setPreferenceScreen(PreferenceScreen)}.

    As a convenience, this fragment implements a click listener for any preference in the current hierarchy, see {@link #onPreferenceTreeClick(PreferenceScreen, Preference)}.

    Developer Guides

    For information about using {@code PreferenceFragment}, read the Settings guide.

    Sample Code

    The following sample code shows a simple preference fragment that is populated from a resource. The resource it loads is:

    {@sample development/samples/ApiDemos/res/xml/preferences.xml preferences}

    The fragment implementation itself simply populates the preferences when created. Note that the preferences framework takes care of loading the current values out of the app preferences and writing them when changed:

    {@sample development/samples/ApiDemos/src/com/example/android/apis/preference/FragmentPreferences.java fragment}
  • see
    Preference
    see
    PreferenceScreen

    Fields Summary
    private static final String
    PREFERENCES_TAG
    private PreferenceManager
    mPreferenceManager
    private android.widget.ListView
    mList
    private boolean
    mHavePrefs
    private boolean
    mInitDone
    private int
    mLayoutResId
    private static final int
    FIRST_REQUEST_CODE
    The starting request code given out to preference framework.
    private static final int
    MSG_BIND_PREFERENCES
    private android.os.Handler
    mHandler
    private final Runnable
    mRequestFocus
    private android.view.View.OnKeyListener
    mListOnKeyListener
    Constructors Summary
    Methods Summary
    public voidaddPreferencesFromIntent(android.content.Intent intent)
    Adds preferences from activities that match the given {@link Intent}.

    param
    intent The {@link Intent} to query activities.

            requirePreferenceManager();
    
            setPreferenceScreen(mPreferenceManager.inflateFromIntent(intent, getPreferenceScreen()));
        
    public voidaddPreferencesFromResource(int preferencesResId)
    Inflates the given XML resource and adds the preference hierarchy to the current preference hierarchy.

    param
    preferencesResId The XML resource ID to inflate.

            requirePreferenceManager();
    
            setPreferenceScreen(mPreferenceManager.inflateFromResource(getActivity(),
                    preferencesResId, getPreferenceScreen()));
        
    private voidbindPreferences()

            final PreferenceScreen preferenceScreen = getPreferenceScreen();
            if (preferenceScreen != null) {
                preferenceScreen.bind(getListView());
            }
            onBindPreferences();
        
    private voidensureList()

            if (mList != null) {
                return;
            }
            View root = getView();
            if (root == null) {
                throw new IllegalStateException("Content view not yet created");
            }
            View rawListView = root.findViewById(android.R.id.list);
            if (!(rawListView instanceof ListView)) {
                throw new RuntimeException(
                        "Content has view with id attribute 'android.R.id.list' "
                        + "that is not a ListView class");
            }
            mList = (ListView)rawListView;
            if (mList == null) {
                throw new RuntimeException(
                        "Your content must have a ListView whose id attribute is " +
                        "'android.R.id.list'");
            }
            mList.setOnKeyListener(mListOnKeyListener);
            mHandler.post(mRequestFocus);
        
    public PreferencefindPreference(java.lang.CharSequence key)
    Finds a {@link Preference} based on its key.

    param
    key The key of the preference to retrieve.
    return
    The {@link Preference} with the key, or null.
    see
    PreferenceGroup#findPreference(CharSequence)

            if (mPreferenceManager == null) {
                return null;
            }
            return mPreferenceManager.findPreference(key);
        
    public android.widget.ListViewgetListView()

    hide

            ensureList();
            return mList;
        
    public PreferenceManagergetPreferenceManager()
    Returns the {@link PreferenceManager} used by this fragment.

    return
    The {@link PreferenceManager}.

            return mPreferenceManager;
        
    public PreferenceScreengetPreferenceScreen()
    Gets the root of the preference hierarchy that this fragment is showing.

    return
    The {@link PreferenceScreen} that is the root of the preference hierarchy.

            return mPreferenceManager.getPreferenceScreen();
        
    public booleanhasListView()

    hide

            if (mList != null) {
                return true;
            }
            View root = getView();
            if (root == null) {
                return false;
            }
            View rawListView = root.findViewById(android.R.id.list);
            if (!(rawListView instanceof ListView)) {
                return false;
            }
            mList = (ListView)rawListView;
            if (mList == null) {
                return false;
            }
            return true;
        
    public voidonActivityCreated(android.os.Bundle savedInstanceState)

            super.onActivityCreated(savedInstanceState);
    
            if (mHavePrefs) {
                bindPreferences();
            }
    
            mInitDone = true;
    
            if (savedInstanceState != null) {
                Bundle container = savedInstanceState.getBundle(PREFERENCES_TAG);
                if (container != null) {
                    final PreferenceScreen preferenceScreen = getPreferenceScreen();
                    if (preferenceScreen != null) {
                        preferenceScreen.restoreHierarchyState(container);
                    }
                }
            }
        
    public voidonActivityResult(int requestCode, int resultCode, android.content.Intent data)

            super.onActivityResult(requestCode, resultCode, data);
    
            mPreferenceManager.dispatchActivityResult(requestCode, resultCode, data);
        
    protected voidonBindPreferences()

    hide

        
    public voidonCreate(android.os.Bundle savedInstanceState)

    
                                   
           
                                                      
                
        
    
        
            
            super.onCreate(savedInstanceState);
            mPreferenceManager = new PreferenceManager(getActivity(), FIRST_REQUEST_CODE);
            mPreferenceManager.setFragment(this);
        
    public android.view.ViewonCreateView(android.view.LayoutInflater inflater, android.view.ViewGroup container, android.os.Bundle savedInstanceState)

    
            TypedArray a = getActivity().obtainStyledAttributes(null,
                    com.android.internal.R.styleable.PreferenceFragment,
                    com.android.internal.R.attr.preferenceFragmentStyle,
                    0);
    
            mLayoutResId = a.getResourceId(com.android.internal.R.styleable.PreferenceFragment_layout,
                    mLayoutResId);
    
            a.recycle();
    
            return inflater.inflate(mLayoutResId, container, false);
        
    public voidonDestroy()

            super.onDestroy();
            mPreferenceManager.dispatchActivityDestroy();
        
    public voidonDestroyView()

            mList = null;
            mHandler.removeCallbacks(mRequestFocus);
            mHandler.removeMessages(MSG_BIND_PREFERENCES);
            super.onDestroyView();
        
    public booleanonPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference)
    {@inheritDoc}

            if (preference.getFragment() != null &&
                    getActivity() instanceof OnPreferenceStartFragmentCallback) {
                return ((OnPreferenceStartFragmentCallback)getActivity()).onPreferenceStartFragment(
                        this, preference);
            }
            return false;
        
    public voidonSaveInstanceState(android.os.Bundle outState)

            super.onSaveInstanceState(outState);
    
            final PreferenceScreen preferenceScreen = getPreferenceScreen();
            if (preferenceScreen != null) {
                Bundle container = new Bundle();
                preferenceScreen.saveHierarchyState(container);
                outState.putBundle(PREFERENCES_TAG, container);
            }
        
    public voidonStart()

            super.onStart();
            mPreferenceManager.setOnPreferenceTreeClickListener(this);
        
    public voidonStop()

            super.onStop();
            mPreferenceManager.dispatchActivityStop();
            mPreferenceManager.setOnPreferenceTreeClickListener(null);
        
    protected voidonUnbindPreferences()

    hide

        
    private voidpostBindPreferences()

            if (mHandler.hasMessages(MSG_BIND_PREFERENCES)) return;
            mHandler.obtainMessage(MSG_BIND_PREFERENCES).sendToTarget();
        
    private voidrequirePreferenceManager()

            if (mPreferenceManager == null) {
                throw new RuntimeException("This should be called after super.onCreate.");
            }
        
    public voidsetPreferenceScreen(PreferenceScreen preferenceScreen)
    Sets the root of the preference hierarchy that this fragment is showing.

    param
    preferenceScreen The root {@link PreferenceScreen} of the preference hierarchy.

            if (mPreferenceManager.setPreferences(preferenceScreen) && preferenceScreen != null) {
                onUnbindPreferences();
                mHavePrefs = true;
                if (mInitDone) {
                    postBindPreferences();
                }
            }