PreferenceFragmentCompat

public abstract class PreferenceFragmentCompat extends Fragment implements PreferenceManager.OnPreferenceTreeClickListener, PreferenceManager.OnDisplayPreferenceDialogListener, PreferenceManager.OnNavigateToScreenListener, DialogPreference.TargetFragment

Known direct subclasses
BaseLeanbackPreferenceFragmentCompat

This fragment provides a preference fragment with leanback-style behavior, suitable for embedding into broader UI elements.

Known indirect subclasses
LeanbackPreferenceFragmentCompat

This fragment provides a fully decorated leanback-style preference fragment, including a list background and header.


A PreferenceFragmentCompat is the entry point to using the Preference library. This Fragment displays a hierarchy of Preference objects to the user. It also handles persisting values to the device. To retrieve an instance of android.content.SharedPreferences that the preference hierarchy in this fragment will use by default, call getDefaultSharedPreferences with a context in the same package as this fragment.

You can define a preference hierarchy as an XML resource, or you can build a hierarchy in code. In both cases you need to use a PreferenceScreen as the root component in your hierarchy.

To inflate from XML, use the setPreferencesFromResource. An example example XML resource is shown further down.

To build a hierarchy from code, use createPreferenceScreen to create the root PreferenceScreen. Once you have added other Preferences to this root screen with addPreference, you then need to set the screen as the root screen in your hierarchy with setPreferenceScreen.

As a convenience, this fragment implements a click listener for any preference in the current hierarchy, see onPreferenceTreeClick.

Sample Code

The following sample code shows a simple settings screen using an XML resource. The XML resource is as follows:

<PreferenceScreen
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">

    <PreferenceCategory
            android:title="@string/basic_preferences">

        <Preference
                android:key="preference"
                android:title="@string/title_basic_preference"
                android:summary="@string/summary_basic_preference"/>

        <Preference
                android:key="stylized"
                android:title="@string/title_stylish_preference"
                android:summary="@string/summary_stylish_preference"/>

        <Preference
                android:key="icon"
                android:title="@string/title_icon_preference"
                android:summary="@string/summary_icon_preference"
                android:icon="@android:drawable/ic_menu_camera"/>

        <Preference
                android:key="single_line_title"
                android:title="@string/title_single_line_title_preference"
                android:summary="@string/summary_single_line_title_preference"
                app:singleLineTitle="true"/>
    </PreferenceCategory>

    <PreferenceCategory
            android:title="@string/widgets">

        <CheckBoxPreference
                android:key="checkbox"
                android:title="@string/title_checkbox_preference"
                android:summary="@string/summary_checkbox_preference"/>

        <SwitchPreferenceCompat
                android:key="switch"
                android:title="@string/title_switch_preference"
                android:summary="@string/summary_switch_preference"/>

        <DropDownPreference
                android:key="dropdown"
                android:title="@string/title_dropdown_preference"
                android:entries="@array/entries"
                app:useSimpleSummaryProvider="true"
                android:entryValues="@array/entry_values"/>

        <SeekBarPreference
                android:key="seekbar"
                android:title="@string/title_seekbar_preference"
                android:max="10"
                android:defaultValue="5"/>
    </PreferenceCategory>

    <PreferenceCategory
            android:title="@string/dialogs">

        <EditTextPreference
                android:key="edittext"
                android:title="@string/title_edittext_preference"
                app:useSimpleSummaryProvider="true"
                android:dialogTitle="@string/dialog_title_edittext_preference"/>

        <ListPreference
                android:key="list"
                android:title="@string/title_list_preference"
                app:useSimpleSummaryProvider="true"
                android:entries="@array/entries"
                android:entryValues="@array/entry_values"
                android:dialogTitle="@string/dialog_title_list_preference"/>

        <MultiSelectListPreference
                android:key="multi_select_list"
                android:title="@string/title_multi_list_preference"
                android:summary="@string/summary_multi_list_preference"
                android:entries="@array/entries"
                android:entryValues="@array/entry_values"
                android:dialogTitle="@string/dialog_title_multi_list_preference"/>
    </PreferenceCategory>

    <PreferenceCategory
            android:key="advanced"
            android:title="@string/advanced_attributes"
            app:initialExpandedChildrenCount="1">

        <Preference
                android:key="expandable"
                android:title="@string/title_expandable_preference"
                android:summary="@string/summary_expandable_preference"/>

        <Preference
                android:title="@string/title_intent_preference"
                android:summary="@string/summary_intent_preference">

            <intent android:action="android.intent.action.VIEW"
                    android:data="http://www.android.com"/>

        </Preference>

        <SwitchPreferenceCompat
                android:key="parent"
                android:title="@string/title_parent_preference"
                android:summary="@string/summary_parent_preference"/>

        <SwitchPreferenceCompat
                android:key="child"
                android:dependency="parent"
                android:title="@string/title_child_preference"
                android:summary="@string/summary_child_preference"/>

        <SwitchPreferenceCompat
                android:key="toggle_summary"
                android:title="@string/title_toggle_summary_preference"
                android:summaryOn="@string/summary_on_toggle_summary_preference"
                android:summaryOff="@string/summary_off_toggle_summary_preference"/>

        <Preference
                android:key="copyable"
                android:title="@string/title_copyable_preference"
                android:summary="@string/summary_copyable_preference"
                android:selectable="false"
                app:enableCopying="true"/>
    </PreferenceCategory>

</PreferenceScreen>

The fragment that loads the XML resource is as follows:

public static class DemoFragment extends PreferenceFragmentCompat {

    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        // Load the preferences from an XML resource
        setPreferencesFromResource(R.xml.preferences, rootKey);
    }
}

Summary

Nested types

Interface that the fragment's containing activity should implement to be able to process preference items that wish to display a dialog.

Interface that the fragment's containing activity should implement to be able to process preference items that wish to switch to a specified fragment.

Interface that the fragment's containing activity should implement to be able to process preference items that wish to switch to a new screen of preferences.

Constants

static final String
ARG_PREFERENCE_ROOT = "androidx.preference.PreferenceFragmentCompat.PREFERENCE_ROOT"

Fragment argument used to specify the tag of the desired root PreferenceScreen object.

Public constructors

Public methods

void
addPreferencesFromResource(@XmlRes int preferencesResId)

Inflates the given XML resource and adds the preference hierarchy to the current preference hierarchy.

@Nullable T

Finds a Preference with the given key.

final RecyclerView
PreferenceManager

Returns the PreferenceManager used by this fragment.

PreferenceScreen

Gets the root of the preference hierarchy that this fragment is showing.

void
onCreate(@Nullable Bundle savedInstanceState)

Called to do initial creation of a fragment.

@NonNull RecyclerView.LayoutManager

Called from onCreateRecyclerView to create the RecyclerView.LayoutManager for the created RecyclerView.

abstract void
onCreatePreferences(
    @Nullable Bundle savedInstanceState,
    @Nullable String rootKey
)

Called during onCreate to supply the preferences for this fragment.

@NonNull RecyclerView
onCreateRecyclerView(
    @NonNull LayoutInflater inflater,
    @NonNull ViewGroup parent,
    @Nullable Bundle savedInstanceState
)

Creates the RecyclerView used to display the preferences.

@NonNull View
onCreateView(
    @NonNull LayoutInflater inflater,
    @Nullable ViewGroup container,
    @Nullable Bundle savedInstanceState
)

Called to have the fragment instantiate its user interface view.

void

Called when the view previously created by onCreateView has been detached from the fragment.

void

Called when a preference in the tree requests to display a dialog.

void

Called by onClick in order to navigate to a new screen of preferences.

boolean

Called when a preference in the tree rooted at this has been clicked.

void

Called to ask the fragment to save its current dynamic state, so it can later be reconstructed in a new instance if its process is restarted.

void

Called when the Fragment is visible to the user.

void

Called when the Fragment is no longer started.

void
onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState)

Called immediately after onCreateView has returned, but before any saved state has been restored in to the view.

void
void
void

Sets the Drawable that will be drawn between each item in the list.

void
setDividerHeight(int height)

Sets the height of the divider that will be drawn between each item in the list.

void

Sets the root of the preference hierarchy that this fragment is showing.

void
setPreferencesFromResource(
    @XmlRes int preferencesResId,
    @Nullable String key
)

Inflates the given XML resource and replaces the current preference hierarchy (if any) with the preference hierarchy rooted at key.

Protected methods

@NonNull RecyclerView.Adapter

Creates the root adapter.

Inherited methods

From androidx.activity.result.ActivityResultCaller
abstract ActivityResultLauncher<I>
<I, O> registerForActivityResult(
    ActivityResultContract<I, O> contract,
    ActivityResultCallback<O> callback
)

Register a request to start an activity for result, designated by the given contract.

From android.content.ComponentCallbacks
abstract void
abstract void
From androidx.fragment.app.Fragment
void
dump(
    @NonNull String prefix,
    @Nullable FileDescriptor fd,
    @NonNull PrintWriter writer,
    @Nullable String[] args
)

Print the Fragments's state into the given stream.

final boolean

Subclasses can not override equals().

final @Nullable FragmentActivity

Return the FragmentActivity this fragment is currently associated with.

boolean

Returns whether the the exit transition and enter transition overlap or not.

boolean

Returns whether the the return transition and reenter transition overlap or not.

final @Nullable Bundle

Return the arguments supplied when the fragment was instantiated, if any.

final @NonNull FragmentManager

Return a private FragmentManager for placing and managing Fragments inside of this Fragment.

@Nullable Context

Return the Context this fragment is currently associated with.

@NonNull CreationExtras

Returns the default CreationExtras that should be passed into ViewModelProvider.Factory.create when no overriding CreationExtras were passed to the ViewModelProvider constructors.

@NonNull ViewModelProvider.Factory

Returns the default ViewModelProvider.Factory that should be used when no custom Factory is provided to the ViewModelProvider constructors.

@Nullable Object

Returns the Transition that will be used to move Views into the initial scene.

@Nullable Object

Returns the Transition that will be used to move Views out of the scene when the fragment is removed, hidden, or detached when not popping the back stack.

final @Nullable FragmentManager

This method is deprecated.

This has been removed in favor of getParentFragmentManager() which throws an IllegalStateException if the FragmentManager is null.

final @Nullable Object

Return the host object of this fragment.

final int

Return the identifier this fragment is known by.

final @NonNull LayoutInflater

Returns the cached LayoutInflater used to inflate Views of this Fragment.

@NonNull Lifecycle

Returns the Lifecycle of the provider.

@NonNull LoaderManager

This method is deprecated.

Use LoaderManager.getInstance(this).

final @Nullable Fragment

Returns the parent Fragment containing this Fragment.

final @NonNull FragmentManager

Return the FragmentManager for interacting with fragments associated with this fragment's activity.

@Nullable Object

Returns the Transition that will be used to move Views in to the scene when returning due to popping a back stack.

final @NonNull Resources

Return requireActivity().getResources().

final boolean

This method is deprecated.

Instead of retaining the Fragment itself, use a non-retained Fragment and keep retained state in a ViewModel attached to that Fragment.

@Nullable Object

Returns the Transition that will be used to move Views out of the scene when the Fragment is preparing to be removed, hidden, or detached because of popping the back stack.

final @NonNull SavedStateRegistry

The SavedStateRegistry owned by this SavedStateRegistryOwner

@Nullable Object

Returns the Transition that will be used for shared elements transferred into the content Scene.

@Nullable Object

Return the Transition that will be used for shared elements transferred back during a pop of the back stack.

final @NonNull String
getString(@StringRes int resId)

Return a localized string from the application's package's default string table.

final @NonNull String
getString(@StringRes int resId, @Nullable Object[] formatArgs)

Return a localized formatted string from the application's package's default string table, substituting the format arguments as defined in java.util.Formatter and format.

final @Nullable String

Get the tag name of the fragment, if specified.

final @Nullable Fragment

This method is deprecated.

Instead of using a target fragment to pass results, use setFragmentResult to deliver results to FragmentResultListener instances registered by other fragments via setFragmentResultListener.

final int

This method is deprecated.

When using the target fragment replacement of setFragmentResultListener and setFragmentResult, consider using setArguments to pass a requestKey if you need to support dynamic request keys.

final @NonNull CharSequence
getText(@StringRes int resId)

Return a localized, styled CharSequence from the application's package's default string table.

boolean

This method is deprecated.

Use setMaxLifecycle instead.

@Nullable View

Get the root view for the fragment's layout (the one returned by onCreateView), if provided.

@NonNull LifecycleOwner

Get a LifecycleOwner that represents the Fragment's View lifecycle.

@NonNull LiveData<LifecycleOwner>

Retrieve a LiveData which allows you to observe the lifecycle of the Fragment's View.

@NonNull ViewModelStore

Returns the ViewModelStore associated with this Fragment

final int

Subclasses can not override hashCode().

static @NonNull Fragment

This method is deprecated.

Use getFragmentFactory and instantiate

static @NonNull Fragment
instantiate(
    @NonNull Context context,
    @NonNull String fname,
    @Nullable Bundle args
)

This method is deprecated.

Use getFragmentFactory and instantiate, manually calling setArguments on the returned Fragment.

final boolean

Return true if the fragment is currently added to its activity.

final boolean

Return true if the fragment has been explicitly detached from the UI.

final boolean

Return true if the fragment has been hidden.

final boolean

Return true if the layout is included as part of an activity view hierarchy via the tag.

final boolean

Return true if this fragment is currently being removed from its activity.

final boolean

Return true if the fragment is in the resumed state.

final boolean

Returns true if this fragment is added and its state has already been saved by its host.

final boolean

Return true if the fragment is currently visible to the user.

void

This method is deprecated.

use onViewCreated for code touching the view created by onCreateView and onCreate for other initialization.

void
onActivityResult(int requestCode, int resultCode, @Nullable Intent data)

This method is deprecated.

This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an ActivityResultContract and the prebuilt contracts for common intents available in androidx.activity.result.contract.ActivityResultContracts, provides hooks for testing, and allow receiving results in separate, testable classes independent from your fragment.

void

This method is deprecated.

See onAttach.

void

Called when a fragment is first attached to its context.

void

This method is deprecated.

The responsibility for listening for fragments being attached has been moved to FragmentManager.

void
boolean

This hook is called whenever an item in a context menu is selected.

@Nullable Animation
@MainThread
onCreateAnimation(int transit, boolean enter, int nextAnim)

Called when a fragment loads an animation.

@Nullable Animator
@MainThread
onCreateAnimator(int transit, boolean enter, int nextAnim)

Called when a fragment loads an animator.

void

Called when a context menu for the view is about to be shown.

void

This method is deprecated.

androidx.activity.ComponentActivity now implements MenuHost, an interface that allows any component, including your activity itself, to add menu items by calling addMenuProvider without forcing all components through this single method override.

void

Called when the fragment is no longer in use.

void

This method is deprecated.

androidx.activity.ComponentActivity now implements MenuHost, an interface that allows any component, including your activity itself, to add menu items by calling addMenuProvider without forcing all components through this single method override.

void

Called when the fragment is no longer attached to its activity.

@NonNull LayoutInflater
onGetLayoutInflater(@Nullable Bundle savedInstanceState)

Returns the LayoutInflater used to inflate Views of this Fragment.

void
@MainThread
onHiddenChanged(boolean hidden)

Called when the hidden state (as returned by isHidden of the fragment or another fragment in its hierarchy has changed.

void
@UiThread
@CallSuper
onInflate(
    @NonNull Activity activity,
    @NonNull AttributeSet attrs,
    @Nullable Bundle savedInstanceState
)

This method is deprecated.

See onInflate.

void
@UiThread
@CallSuper
onInflate(
    @NonNull Context context,
    @NonNull AttributeSet attrs,
    @Nullable Bundle savedInstanceState
)

Called when a fragment is being created as part of a view layout inflation, typically from setting the content view of an activity.

void
void
onMultiWindowModeChanged(boolean isInMultiWindowMode)

Called when the Fragment's activity changes from fullscreen mode to multi-window mode and visa-versa.

boolean

This method is deprecated.

androidx.activity.ComponentActivity now implements MenuHost, an interface that allows any component, including your activity itself, to add menu items by calling addMenuProvider without forcing all components through this single method override.

void

This method is deprecated.

androidx.activity.ComponentActivity now implements MenuHost, an interface that allows any component, including your activity itself, to add menu items by calling addMenuProvider without forcing all components through this single method override.

void

Called when the Fragment is no longer resumed.

void
onPictureInPictureModeChanged(boolean isInPictureInPictureMode)

Called by the system when the activity changes to and from picture-in-picture mode.

void

This method is deprecated.

androidx.activity.ComponentActivity now implements MenuHost, an interface that allows any component, including your activity itself, to add menu items by calling addMenuProvider without forcing all components through this single method override.

void
@MainThread
onPrimaryNavigationFragmentChanged(
    boolean isPrimaryNavigationFragment
)

Callback for when the primary navigation state of this Fragment has changed.

void
onRequestPermissionsResult(
    int requestCode,
    @NonNull String[] permissions,
    @NonNull int[] grantResults
)

This method is deprecated.

This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an ActivityResultContract and the prebuilt contracts for common intents available in androidx.activity.result.contract.ActivityResultContracts, provides hooks for testing, and allow receiving results in separate, testable classes independent from your fragment.

void

Called when the fragment is visible to the user and actively running.

void

Called when all saved state has been restored into the view hierarchy of the fragment.

void

Postpone the entering Fragment transition until startPostponedEnterTransition or executePendingTransactions has been called.

final void
postponeEnterTransition(long duration, @NonNull TimeUnit timeUnit)

Postpone the entering Fragment transition for a given amount of time and then call startPostponedEnterTransition.

final @NonNull ActivityResultLauncher<I>
@MainThread
<I, O> registerForActivityResult(
    @NonNull ActivityResultContract<I, O> contract,
    @NonNull ActivityResultCallback<O> callback
)

Register a request to start an activity for result, designated by the given contract.

final @NonNull ActivityResultLauncher<I>
@MainThread
<I, O> registerForActivityResult(
    @NonNull ActivityResultContract<I, O> contract,
    @NonNull ActivityResultRegistry registry,
    @NonNull ActivityResultCallback<O> callback
)

Register a request to start an activity for result, designated by the given contract.

void

Registers a context menu to be shown for the given view (multiple views can show the context menu).

final void
requestPermissions(@NonNull String[] permissions, int requestCode)

This method is deprecated.

This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an ActivityResultContract and the prebuilt contracts for common intents available in androidx.activity.result.contract.ActivityResultContracts, provides hooks for testing, and allow receiving results in separate, testable classes independent from your fragment.

final @NonNull FragmentActivity

Return the FragmentActivity this fragment is currently associated with.

final @NonNull Bundle

Return the arguments supplied when the fragment was instantiated.

final @NonNull Context

Return the Context this fragment is currently associated with.

final @NonNull FragmentManager

This method is deprecated.

This has been renamed to getParentFragmentManager() to make it clear that you are accessing the FragmentManager that contains this Fragment and not the FragmentManager associated with child Fragments.

final @NonNull Object

Return the host object of this fragment.

final @NonNull Fragment

Returns the parent Fragment containing this Fragment.

final @NonNull View

Get the root view for the fragment's layout (the one returned by onCreateView).

void

Sets whether the the exit transition and enter transition overlap or not.

void

Sets whether the the return transition and reenter transition overlap or not.

void

Supply the construction arguments for this fragment.

void

When custom transitions are used with Fragments, the enter transition callback is called when this Fragment is attached or detached when not popping the back stack.

void

Sets the Transition that will be used to move Views into the initial scene.

void

When custom transitions are used with Fragments, the exit transition callback is called when this Fragment is attached or detached when popping the back stack.

void

Sets the Transition that will be used to move Views out of the scene when the fragment is removed, hidden, or detached when not popping the back stack.

void
setHasOptionsMenu(boolean hasMenu)

This method is deprecated.

This method is no longer needed when using a MenuProvider to provide a Menu to your activity, which replaces onCreateOptionsMenu as the recommended way to provide a consistent, optionally Lifecycle-aware, and modular way to handle menu creation and item selection.

void

Set the initial saved state that this Fragment should restore itself from when first being constructed, as returned by FragmentManager.saveFragmentInstanceState.

void
setMenuVisibility(boolean menuVisible)

Set a hint for whether this fragment's menu should be visible.

void

Sets the Transition that will be used to move Views in to the scene when returning due to popping a back stack.

void
setRetainInstance(boolean retain)

This method is deprecated.

Instead of retaining the Fragment itself, use a non-retained Fragment and keep retained state in a ViewModel attached to that Fragment.

void

Sets the Transition that will be used to move Views out of the scene when the Fragment is preparing to be removed, hidden, or detached because of popping the back stack.

void

Sets the Transition that will be used for shared elements transferred into the content Scene.

void

Sets the Transition that will be used for shared elements transferred back during a pop of the back stack.

void
setTargetFragment(@Nullable Fragment fragment, int requestCode)

This method is deprecated.

Instead of using a target fragment to pass results, the fragment requesting a result should use setFragmentResultListener to register a FragmentResultListener with a requestKey using its parent fragment manager.

void
setUserVisibleHint(boolean isVisibleToUser)

This method is deprecated.

If you are manually calling this method, use setMaxLifecycle instead.

boolean

Gets whether you should show UI with rationale before requesting a permission.

void

Call startActivity from the fragment's containing Activity.

void

Call startActivity from the fragment's containing Activity.

void
startActivityForResult(@NonNull Intent intent, int requestCode)

This method is deprecated.

This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an ActivityResultContract and the prebuilt contracts for common intents available in androidx.activity.result.contract.ActivityResultContracts, provides hooks for testing, and allow receiving results in separate, testable classes independent from your fragment.

void
startActivityForResult(
    @NonNull Intent intent,
    int requestCode,
    @Nullable Bundle options
)

This method is deprecated.

This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an ActivityResultContract and the prebuilt contracts for common intents available in androidx.activity.result.contract.ActivityResultContracts, provides hooks for testing, and allow receiving results in separate, testable classes independent from your fragment.

void
startIntentSenderForResult(
    @NonNull IntentSender intent,
    int requestCode,
    @Nullable Intent fillInIntent,
    int flagsMask,
    int flagsValues,
    int extraFlags,
    @Nullable Bundle options
)

This method is deprecated.

This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an ActivityResultContract and the prebuilt contracts for common intents available in androidx.activity.result.contract.ActivityResultContracts, provides hooks for testing, and allow receiving results in separate, testable classes independent from your fragment.

void

Begin postponed transitions after postponeEnterTransition was called.

@NonNull String
void

Prevents a context menu to be shown for the given view.

From androidx.lifecycle.HasDefaultViewModelProviderFactory
CreationExtras

Returns the default CreationExtras that should be passed into ViewModelProvider.Factory.create when no overriding CreationExtras were passed to the ViewModelProvider constructors.

abstract ViewModelProvider.Factory

Returns the default ViewModelProvider.Factory that should be used when no custom Factory is provided to the ViewModelProvider constructors.

From androidx.lifecycle.LifecycleOwner
abstract Lifecycle

Returns the Lifecycle of the provider.

From androidx.savedstate.SavedStateRegistryOwner
abstract SavedStateRegistry

The SavedStateRegistry owned by this SavedStateRegistryOwner

From android.view.View.OnCreateContextMenuListener
abstract void
From androidx.lifecycle.ViewModelStoreOwner

Constants

ARG_PREFERENCE_ROOT

Added in 1.0.0
public static final String ARG_PREFERENCE_ROOT = "androidx.preference.PreferenceFragmentCompat.PREFERENCE_ROOT"

Fragment argument used to specify the tag of the desired root PreferenceScreen object.

Public constructors

PreferenceFragmentCompat

Added in 1.0.0
public PreferenceFragmentCompat()

Public methods

addPreferencesFromResource

Added in 1.0.0
public void addPreferencesFromResource(@XmlRes int preferencesResId)

Inflates the given XML resource and adds the preference hierarchy to the current preference hierarchy.

Parameters
@XmlRes int preferencesResId

The XML resource ID to inflate

findPreference

Added in 1.3.0-alpha01
public @Nullable T <T extends Preference> findPreference(@NonNull CharSequence key)

Finds a Preference with the given key. Returns null if no Preference could be found with the given key.

Parameters
@NonNull CharSequence key

The key of the Preference to retrieve

Returns
@Nullable T

The Preference with the key, or null

See also
findPreference

getListView

Added in 1.0.0
public final RecyclerView getListView()

getPreferenceManager

Added in 1.0.0
public PreferenceManager getPreferenceManager()

Returns the PreferenceManager used by this fragment.

Returns
PreferenceManager

The PreferenceManager used by this fragment

getPreferenceScreen

Added in 1.0.0
public PreferenceScreen getPreferenceScreen()

Gets the root of the preference hierarchy that this fragment is showing.

Returns
PreferenceScreen

The PreferenceScreen that is the root of the preference hierarchy

onCreate

public void onCreate(@Nullable Bundle savedInstanceState)

Called to do initial creation of a fragment. This is called after onAttach and before onCreateView.

Note that this can be called while the fragment's activity is still in the process of being created. As such, you can not rely on things like the activity's content view hierarchy being initialized at this point. If you want to do work once the activity itself is created, add a androidx.lifecycle.LifecycleObserver on the activity's Lifecycle, removing it when it receives the CREATED callback.

Any restored child fragments will be created before the base Fragment.onCreate method returns.

Parameters
@Nullable Bundle savedInstanceState

If the fragment is being re-created from a previous saved state, this is the state.

onCreateLayoutManager

Added in 1.0.0
public @NonNull RecyclerView.LayoutManager onCreateLayoutManager()

Called from onCreateRecyclerView to create the RecyclerView.LayoutManager for the created RecyclerView.

onCreatePreferences

Added in 1.0.0
public abstract void onCreatePreferences(
    @Nullable Bundle savedInstanceState,
    @Nullable String rootKey
)

Called during onCreate to supply the preferences for this fragment. Subclasses are expected to call setPreferenceScreen either directly or via helper methods such as addPreferencesFromResource.

Parameters
@Nullable Bundle savedInstanceState

If the fragment is being re-created from a previous saved state, this is the state.

@Nullable String rootKey

If non-null, this preference fragment should be rooted at the PreferenceScreen with this key.

onCreateRecyclerView

Added in 1.0.0
public @NonNull RecyclerView onCreateRecyclerView(
    @NonNull LayoutInflater inflater,
    @NonNull ViewGroup parent,
    @Nullable Bundle savedInstanceState
)

Creates the RecyclerView used to display the preferences. Subclasses may override this to return a customized RecyclerView.

Parameters
@NonNull LayoutInflater inflater

The LayoutInflater object that can be used to inflate the RecyclerView.

@NonNull ViewGroup parent

The parent ViewGroup that the RecyclerView will be attached to. This method should not add the view itself, but this can be used to generate the layout params of the view.

@Nullable Bundle savedInstanceState

If non-null, this view is being re-constructed from a previous saved state as given here.

Returns
@NonNull RecyclerView

A new RecyclerView object to be placed into the view hierarchy

onCreateView

public @NonNull View onCreateView(
    @NonNull LayoutInflater inflater,
    @Nullable ViewGroup container,
    @Nullable Bundle savedInstanceState
)

Called to have the fragment instantiate its user interface view. This is optional, and non-graphical fragments can return null. This will be called between onCreate and onViewCreated.

A default View can be returned by calling Fragment in your constructor. Otherwise, this method returns null.

It is recommended to only inflate the layout in this method and move logic that operates on the returned View to onViewCreated.

If you return a View from here, you will later be called in onDestroyView when the view is being released.

Parameters
@NonNull LayoutInflater inflater

The LayoutInflater object that can be used to inflate any views in the fragment,

@Nullable ViewGroup container

If non-null, this is the parent view that the fragment's UI should be attached to. The fragment should not add the view itself, but this can be used to generate the LayoutParams of the view.

@Nullable Bundle savedInstanceState

If non-null, this fragment is being re-constructed from a previous saved state as given here.

Returns
@NonNull View

Return the View for the fragment's UI, or null.

onDestroyView

public void onDestroyView()

Called when the view previously created by onCreateView has been detached from the fragment. The next time the fragment needs to be displayed, a new view will be created. This is called after onStop and before onDestroy. It is called regardless of whether onCreateView returned a non-null view. Internally it is called after the view's state has been saved but before it has been removed from its parent.

onDisplayPreferenceDialog

Added in 1.3.0-alpha01
public void onDisplayPreferenceDialog(@NonNull Preference preference)

Called when a preference in the tree requests to display a dialog. Subclasses should override this method to display custom dialogs or to handle dialogs for custom preference classes.

Parameters
@NonNull Preference preference

The Preference object requesting the dialog

onNavigateToScreen

Added in 1.3.0-alpha01
public void onNavigateToScreen(@NonNull PreferenceScreen preferenceScreen)

Called by onClick in order to navigate to a new screen of preferences. Calls onPreferenceStartScreen if the target fragment or containing activity implements PreferenceFragmentCompat.OnPreferenceStartScreenCallback.

Parameters
@NonNull PreferenceScreen preferenceScreen

The PreferenceScreen to navigate to

onPreferenceTreeClick

Added in 1.3.0-alpha01
public boolean onPreferenceTreeClick(@NonNull Preference preference)

Called when a preference in the tree rooted at this has been clicked.

onSaveInstanceState

public void onSaveInstanceState(@NonNull Bundle outState)

Called to ask the fragment to save its current dynamic state, so it can later be reconstructed in a new instance if its process is restarted. If a new instance of the fragment later needs to be created, the data you place in the Bundle here will be available in the Bundle given to onCreate, onCreateView, and onViewCreated.

This corresponds to Activity.onSaveInstanceState(Bundle) and most of the discussion there applies here as well. Note however: this method may be called at any time before onDestroy. There are many situations where a fragment may be mostly torn down (such as when placed on the back stack with no UI showing), but its state will not be saved until its owning activity actually needs to save its state.

Parameters
@NonNull Bundle outState

Bundle in which to place your saved state.

onStart

public void onStart()

Called when the Fragment is visible to the user. This is generally tied to Activity.onStart of the containing Activity's lifecycle.

onStop

public void onStop()

Called when the Fragment is no longer started. This is generally tied to Activity.onStop of the containing Activity's lifecycle.

onViewCreated

public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState)

Called immediately after onCreateView has returned, but before any saved state has been restored in to the view. This gives subclasses a chance to initialize themselves once they know their view hierarchy has been completely created. The fragment's view hierarchy is not however attached to its parent at this point.

Parameters
@NonNull View view

The View returned by onCreateView.

@Nullable Bundle savedInstanceState

If non-null, this fragment is being re-constructed from a previous saved state as given here.

scrollToPreference

Added in 1.0.0
public void scrollToPreference(@NonNull String key)

scrollToPreference

Added in 1.0.0
public void scrollToPreference(@NonNull Preference preference)

setDivider

Added in 1.0.0
public void setDivider(@Nullable Drawable divider)

Sets the Drawable that will be drawn between each item in the list.

Note: If the drawable does not have an intrinsic height, you should also call setDividerHeight.

Parameters
@Nullable Drawable divider

The drawable to use divider

setDividerHeight

Added in 1.0.0
public void setDividerHeight(int height)

Sets the height of the divider that will be drawn between each item in the list. Calling this will override the intrinsic height as set by setDivider.

Parameters
int height

The new height of the divider in pixels dividerHeight

setPreferenceScreen

Added in 1.0.0
public void setPreferenceScreen(PreferenceScreen preferenceScreen)

Sets the root of the preference hierarchy that this fragment is showing.

Parameters
PreferenceScreen preferenceScreen

The root PreferenceScreen of the preference hierarchy

setPreferencesFromResource

Added in 1.0.0
public void setPreferencesFromResource(
    @XmlRes int preferencesResId,
    @Nullable String key
)

Inflates the given XML resource and replaces the current preference hierarchy (if any) with the preference hierarchy rooted at key.

Parameters
@XmlRes int preferencesResId

The XML resource ID to inflate

@Nullable String key

The preference key of the PreferenceScreen to use as the root of the preference hierarchy, or null to use the root PreferenceScreen.

Protected methods

onCreateAdapter

Added in 1.0.0
protected @NonNull RecyclerView.Adapter onCreateAdapter(@NonNull PreferenceScreen preferenceScreen)

Creates the root adapter.

Parameters
@NonNull PreferenceScreen preferenceScreen

The PreferenceScreen object to create the adapter for

Returns
@NonNull RecyclerView.Adapter

An adapter that contains the preferences contained in this PreferenceScreen