PreferenceFragmentCompat


abstract class PreferenceFragmentCompat : Fragment, 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

const 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 functions

Unit

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

T?

Finds a Preference with the given key.

RecyclerView!
PreferenceManager!

Returns the PreferenceManager used by this fragment.

PreferenceScreen!

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

Unit
onCreate(savedInstanceState: Bundle?)

Called to do initial creation of a fragment.

RecyclerView.LayoutManager

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

abstract Unit
onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?)

Called during onCreate to supply the preferences for this fragment.

RecyclerView
onCreateRecyclerView(
    inflater: LayoutInflater,
    parent: ViewGroup,
    savedInstanceState: Bundle?
)

Creates the RecyclerView used to display the preferences.

View
onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
)

Called to have the fragment instantiate its user interface view.

Unit

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

Unit

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

Unit

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.

Unit

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.

Unit

Called when the Fragment is visible to the user.

Unit

Called when the Fragment is no longer started.

Unit
onViewCreated(view: View, savedInstanceState: Bundle?)

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

Unit
Unit
Unit
setDivider(divider: Drawable?)

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

Unit

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

Unit

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

Unit
setPreferencesFromResource(preferencesResId: @XmlRes Int, key: String?)

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

Protected functions

RecyclerView.Adapter
onCreateAdapter(preferenceScreen: PreferenceScreen)

Creates the root adapter.

Inherited functions

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

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

From android.content.ComponentCallbacks
From androidx.fragment.app.Fragment
Unit
dump(
    prefix: String,
    fd: FileDescriptor?,
    writer: PrintWriter,
    args: Array<String!>?
)

Print the Fragments's state into the given stream.

Boolean
equals(o: Any?)

Subclasses can not override equals().

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.

Bundle?

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

FragmentManager

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

Context?

Return the Context this fragment is currently associated with.

CreationExtras

The Fragment's arguments when this is first called will be used as the defaults to any androidx.lifecycle.SavedStateHandle passed to a view model created using this extra.

ViewModelProvider.Factory
Any?

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

Any?

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.

FragmentManager?

This function is deprecated.

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

Any?

Return the host object of this fragment.

Int

Return the identifier this fragment is known by.

LayoutInflater

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

Lifecycle

Overriding this method is no longer supported and this method will be made final in a future version of Fragment.

LoaderManager

This function is deprecated.

Use LoaderManager.getInstance(this).

Fragment?

Returns the parent Fragment containing this Fragment.

FragmentManager

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

Any?

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

Resources

Return requireActivity().getResources().

Boolean

This function is deprecated.

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

Any?

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.

SavedStateRegistry
Any?

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

Any?

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

String

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

String
getString(resId: @StringRes Int, formatArgs: Array<Any!>?)

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.

String?

Get the tag name of the fragment, if specified.

Fragment?

This function 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.

Int

This function 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.

CharSequence

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

Boolean

This function is deprecated.

Use setMaxLifecycle instead.

View?

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

LifecycleOwner

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

LiveData<LifecycleOwner!>

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

ViewModelStore

Returns the ViewModelStore associated with this Fragment

Int

Subclasses can not override hashCode().

java-static Fragment
instantiate(context: Context, fname: String)

This function is deprecated.

Use getFragmentFactory and instantiate

java-static Fragment
instantiate(context: Context, fname: String, args: Bundle?)

This function is deprecated.

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

Boolean

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

Boolean

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

Boolean

Return true if the fragment has been hidden.

Boolean

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

Boolean

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

Boolean

Return true if the fragment is in the resumed state.

Boolean

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

Boolean

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

Unit

This function is deprecated.

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

Unit
onActivityResult(requestCode: Int, resultCode: Int, data: Intent?)

This function 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.

Unit

This function is deprecated.

See onAttach.

Unit

Called when a fragment is first attached to its context.

Unit

This function is deprecated.

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

Unit
Boolean

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

Animation?
@MainThread
onCreateAnimation(transit: Int, enter: Boolean, nextAnim: Int)

Called when a fragment loads an animation.

Animator?
@MainThread
onCreateAnimator(transit: Int, enter: Boolean, nextAnim: Int)

Called when a fragment loads an animator.

Unit
@MainThread
onCreateContextMenu(
    menu: ContextMenu,
    v: View,
    menuInfo: ContextMenu.ContextMenuInfo?
)

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

Unit

This function 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.

Unit

Called when the fragment is no longer in use.

Unit

This function 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.

Unit

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

LayoutInflater
onGetLayoutInflater(savedInstanceState: Bundle?)

Returns the LayoutInflater used to inflate Views of this Fragment.

Unit

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

Unit
@UiThread
@CallSuper
onInflate(
    activity: Activity,
    attrs: AttributeSet,
    savedInstanceState: Bundle?
)

This function is deprecated.

See onInflate.

Unit
@UiThread
@CallSuper
onInflate(
    context: Context,
    attrs: AttributeSet,
    savedInstanceState: Bundle?
)

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

Unit
Unit
onMultiWindowModeChanged(isInMultiWindowMode: Boolean)

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

Boolean

This function 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.

Unit

This function 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.

Unit

Called when the Fragment is no longer resumed.

Unit
onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean)

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

Unit

This function 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.

Unit
@MainThread
onPrimaryNavigationFragmentChanged(
    isPrimaryNavigationFragment: Boolean
)

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

Unit
onRequestPermissionsResult(
    requestCode: Int,
    permissions: Array<String!>,
    grantResults: IntArray
)

This function 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.

Unit

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

Unit

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

Unit

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

Unit
postponeEnterTransition(duration: Long, timeUnit: TimeUnit)

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

ActivityResultLauncher<I!>
@MainThread
<I, O> registerForActivityResult(
    contract: ActivityResultContract<I!, O!>,
    callback: ActivityResultCallback<O!>
)

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

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

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

Unit

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

Unit
requestPermissions(permissions: Array<String!>, requestCode: Int)

This function 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.

FragmentActivity

Return the FragmentActivity this fragment is currently associated with.

Bundle

Return the arguments supplied when the fragment was instantiated.

Context

Return the Context this fragment is currently associated with.

FragmentManager

This function 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.

Any

Return the host object of this fragment.

Fragment

Returns the parent Fragment containing this Fragment.

View

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

Unit

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

Unit

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

Unit

Supply the construction arguments for this fragment.

Unit

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.

Unit
setEnterTransition(transition: Any?)

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

Unit

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.

Unit
setExitTransition(transition: Any?)

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.

Unit

This function 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.

Unit

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

Unit
setMenuVisibility(menuVisible: Boolean)

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

Unit
setReenterTransition(transition: Any?)

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

Unit

This function is deprecated.

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

Unit
setReturnTransition(transition: Any?)

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.

Unit

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

Unit

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

Unit
setTargetFragment(fragment: Fragment?, requestCode: Int)

This function 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.

Unit
setUserVisibleHint(isVisibleToUser: Boolean)

This function 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.

Unit

Call startActivity from the fragment's containing Activity.

Unit
startActivity(intent: Intent, options: Bundle?)

Call startActivity from the fragment's containing Activity.

Unit
startActivityForResult(intent: Intent, requestCode: Int)

This function 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.

Unit
startActivityForResult(intent: Intent, requestCode: Int, options: Bundle?)

This function 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.

Unit
startIntentSenderForResult(
    intent: IntentSender,
    requestCode: Int,
    fillInIntent: Intent?,
    flagsMask: Int,
    flagsValues: Int,
    extraFlags: Int,
    options: Bundle?
)

This function 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.

Unit

Begin postponed transitions after postponeEnterTransition was called.

String
Unit

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

From androidx.lifecycle.HasDefaultViewModelProviderFactory
From androidx.lifecycle.LifecycleOwner
abstract Lifecycle!
From androidx.savedstate.SavedStateRegistryOwner
From android.view.View.OnCreateContextMenuListener
abstract Unit
onCreateContextMenu(
    p: ContextMenu!,
    p1: View!,
    p2: ContextMenu.ContextMenuInfo!
)
From androidx.lifecycle.ViewModelStoreOwner

Constants

ARG_PREFERENCE_ROOT

Added in 1.0.0
const val ARG_PREFERENCE_ROOT = "androidx.preference.PreferenceFragmentCompat.PREFERENCE_ROOT": String!

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

Public constructors

PreferenceFragmentCompat

Added in 1.0.0
PreferenceFragmentCompat()

Public functions

addPreferencesFromResource

Added in 1.0.0
fun addPreferencesFromResource(preferencesResId: @XmlRes Int): Unit

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

Parameters
preferencesResId: @XmlRes Int

The XML resource ID to inflate

findPreference

Added in 1.3.0-alpha01
fun <T : Preference?> findPreference(key: CharSequence): T?

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

Parameters
key: CharSequence

The key of the Preference to retrieve

Returns
T?

The Preference with the key, or null

See also
findPreference

getListView

Added in 1.0.0
fun getListView(): RecyclerView!

getPreferenceManager

Added in 1.0.0
fun getPreferenceManager(): PreferenceManager!

Returns the PreferenceManager used by this fragment.

Returns
PreferenceManager!

The PreferenceManager used by this fragment

getPreferenceScreen

Added in 1.0.0
fun getPreferenceScreen(): PreferenceScreen!

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

fun onCreate(savedInstanceState: Bundle?): Unit

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
savedInstanceState: Bundle?

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

onCreateLayoutManager

Added in 1.0.0
fun onCreateLayoutManager(): RecyclerView.LayoutManager

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

onCreatePreferences

Added in 1.0.0
abstract fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?): Unit

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
savedInstanceState: Bundle?

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

rootKey: String?

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

onCreateRecyclerView

Added in 1.0.0
fun onCreateRecyclerView(
    inflater: LayoutInflater,
    parent: ViewGroup,
    savedInstanceState: Bundle?
): RecyclerView

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

Parameters
inflater: LayoutInflater

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

parent: ViewGroup

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.

savedInstanceState: Bundle?

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

Returns
RecyclerView

A new RecyclerView object to be placed into the view hierarchy

onCreateView

fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View

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
inflater: LayoutInflater

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

container: ViewGroup?

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.

savedInstanceState: Bundle?

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

Returns
View

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

onDestroyView

fun onDestroyView(): Unit

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
fun onDisplayPreferenceDialog(preference: Preference): Unit

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
preference: Preference

The Preference object requesting the dialog

onNavigateToScreen

Added in 1.3.0-alpha01
fun onNavigateToScreen(preferenceScreen: PreferenceScreen): Unit

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
preferenceScreen: PreferenceScreen

The PreferenceScreen to navigate to

onPreferenceTreeClick

Added in 1.3.0-alpha01
fun onPreferenceTreeClick(preference: Preference): Boolean

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

onSaveInstanceState

fun onSaveInstanceState(outState: Bundle): Unit

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
outState: Bundle

Bundle in which to place your saved state.

onStart

fun onStart(): Unit

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

onStop

fun onStop(): Unit

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

onViewCreated

fun onViewCreated(view: View, savedInstanceState: Bundle?): Unit

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
view: View

The View returned by onCreateView.

savedInstanceState: Bundle?

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

scrollToPreference

Added in 1.0.0
fun scrollToPreference(key: String): Unit

scrollToPreference

Added in 1.0.0
fun scrollToPreference(preference: Preference): Unit

setDivider

Added in 1.0.0
fun setDivider(divider: Drawable?): Unit

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
divider: Drawable?

The drawable to use divider

setDividerHeight

Added in 1.0.0
fun setDividerHeight(height: Int): Unit

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
height: Int

The new height of the divider in pixels dividerHeight

setPreferenceScreen

Added in 1.0.0
fun setPreferenceScreen(preferenceScreen: PreferenceScreen!): Unit

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
fun setPreferencesFromResource(preferencesResId: @XmlRes Int, key: String?): Unit

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

Parameters
preferencesResId: @XmlRes Int

The XML resource ID to inflate

key: String?

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

Protected functions

onCreateAdapter

Added in 1.0.0
protected fun onCreateAdapter(preferenceScreen: PreferenceScreen): RecyclerView.Adapter

Creates the root adapter.

Parameters
preferenceScreen: PreferenceScreen

The PreferenceScreen object to create the adapter for

Returns
RecyclerView.Adapter

An adapter that contains the preferences contained in this PreferenceScreen