Preference


public class Preference implements Comparable

Known direct subclasses
DialogPreference

A base class for Preferences that are dialog-based.

PreferenceGroup

A container for multiple Preferences.

SeekBarPreference

Preference based on android.preference.SeekBarPreference but uses support preference as a base .

TwoStatePreference

Common base class for preferences that have two selectable states, save a boolean value, and may have dependent preferences that are enabled/disabled based on the current state.

Known indirect subclasses
CheckBoxPreference

A Preference that provides checkbox widget functionality.

DropDownPreference

A ListPreference that presents the options in a drop down menu rather than a dialog.

EditTextPreference

A DialogPreference that shows a EditText in the dialog.

ListPreference

A Preference that displays a list of entries as a dialog.

MultiSelectListPreference

A Preference that displays a list of entries as a dialog.

PreferenceCategory

A container that is used to group similar Preferences.

PreferenceScreen

A top-level container that represents a settings screen.

SwitchPreferenceCompat

A Preference that provides a two-state toggleable option.

SwitchPreference

A Preference that provides a two-state toggleable option.


The basic building block that represents an individual setting displayed to a user in the preference hierarchy. This class provides the data that will be displayed to the user and has a reference to the SharedPreferences or PreferenceDataStore instance that persists the preference's values.

When specifying a preference hierarchy in XML, each element can point to a subclass of Preference, similar to the view hierarchy and layouts.

This class contains a key that that represents the key that is used to persist the value to the device. It is up to the subclass to decide how to store the value.

name android:icon

name android:key

name android:title

name android:summary

name android:order

name android:fragment

name android:layout

name android:widgetLayout

name android:enabled

name android:selectable

name android:dependency

name android:persistent

name android:defaultValue

name android:shouldDisableView

name android:singleLineTitle

name android:iconSpaceReserved

Summary

Nested types

A base class for managing the instance state of a Preference.

Interface definition for a callback to be invoked when the value of this Preference has been changed by the user and is about to be set and/or persisted.

Interface definition for a callback to be invoked when a Preference is clicked.

public interface Preference.SummaryProvider<T extends Preference>

Interface definition for a callback to be invoked when the summary of this Preference is requested (typically when this preference is added to the hierarchy or its value is updated).

Constants

static final int
DEFAULT_ORDER = 2147483647

Specify for setOrder if a specific order is not required.

Public constructors

Constructor to create a preference.

Constructor that is called when inflating a preference from XML.

Preference(
    @NonNull Context context,
    @Nullable AttributeSet attrs,
    int defStyleAttr
)

Perform inflation from XML and apply a class-specific base style.

Preference(
    @NonNull Context context,
    @Nullable AttributeSet attrs,
    int defStyleAttr,
    int defStyleRes
)

Perform inflation from XML and apply a class-specific base style.

Public methods

boolean

Call this method after the user changes the preference, but before the internal state is set.

int

Compares preference objects based on order (if set), otherwise alphabetically on the titles.

@NonNull Context

Returns the Context of this preference.

@Nullable String

Returns the key of the dependency on this preference.

@NonNull Bundle

Return the extras Bundle object associated with this preference, creating a new Bundle if there currently isn't one.

@Nullable String

Return the fragment class name associated with this preference.

@Nullable Drawable

Returns the icon of this preference.

@Nullable Intent

Return the Intent associated with this preference.

String

Gets the key for this preference, which is also the key used for storing values into SharedPreferences or PreferenceDataStore.

final int

Gets the layout resource that will be shown as the View for this preference.

@Nullable Preference.OnPreferenceChangeListener

Returns the callback to be invoked when this preference is changed by the user (but before the internal state has been updated).

@Nullable Preference.OnPreferenceClickListener

Returns the callback to be invoked when this preference is clicked.

int

Gets the order of this preference with respect to other preference objects on the same level.

@Nullable PreferenceGroup

Returns the PreferenceGroup which is this preference assigned to or null if this preference is not assigned to any group or is a root preference.

Set<String>
getPersistedStringSet(Set<String> defaultReturnValue)

Attempts to get a persisted set of Strings if this preference is persistent.

@Nullable PreferenceDataStore

Returns PreferenceDataStore used by this preference.

PreferenceManager

Gets the PreferenceManager that manages this preference object's tree.

@Nullable SharedPreferences

Returns the SharedPreferences where this preference can read its value(s).

boolean

Checks whether this preference should disable its view when it's action is disabled.

@Nullable CharSequence

Returns the summary of this preference.

final @Nullable Preference.SummaryProvider

Returns the SummaryProvider used to configure the summary of this preference.

@Nullable CharSequence

Returns the title of this preference.

final int

Gets the layout resource for the controllable widget portion of this preference.

boolean

Checks whether this preference has a valid key.

boolean

Returns whether the summary of this preference can be copied to the clipboard by long pressing on the preference.

boolean

Checks whether this preference should be enabled in the list.

boolean

Returns whether the space of this preference icon view is reserved.

boolean

Checks whether this preference is persistent.

boolean

Checks whether this preference should be selectable in the list.

final boolean

Checks whether this preference is shown to the user in the hierarchy.

boolean

Gets whether the title of this preference is constrained to a single line.

final boolean

Checks whether this preference should be visible to the user.

void
notifyDependencyChange(boolean disableDependents)

Notifies any listening dependents of a change that affects the dependency.

void

Called when the preference hierarchy has been attached to the list of preferences.

void

Binds the created View to the data for this preference.

void
onDependencyChanged(
    @NonNull Preference dependency,
    boolean disableDependent
)

Called when the dependency changes.

void

Called when the preference hierarchy has been detached from the list of preferences.

void

This method is deprecated.

Preferences aren't views.

void
onParentChanged(@NonNull Preference parent, boolean disableChild)

Called when the implicit parent dependency changes.

@Nullable Bundle

Return the extras Bundle object associated with this preference, returning null if there is not currently one.

boolean

Attempts to persist a set of Strings if this preference is persistent.

void

Restore this preference hierarchy's previously saved state from the given container.

void

Store this preference hierarchy's frozen state into the given container.

void
setCopyingEnabled(boolean enabled)

Sets whether the summary of this preference can be copied to the clipboard by long pressing on the preference.

void
setDefaultValue(Object defaultValue)

Sets the default value for this preference, which will be set either if persistence is off or persistence is on and the preference is not found in the persistent storage.

void
setDependency(@Nullable String dependencyKey)

Sets the key of a preference that this preference will depend on.

void
setEnabled(boolean enabled)

Sets whether this preference is enabled.

void

Sets the class name of a fragment to be shown when this preference is clicked.

void

Sets the icon for this preference with a Drawable.

void
setIcon(int iconResId)

Sets the icon for this preference with a resource ID.

void
setIconSpaceReserved(boolean iconSpaceReserved)

Sets whether to reserve the space of this preference icon view when no icon is provided.

void

Sets an Intent to be used for startActivity when this preference is clicked.

void

Sets the key for this preference, which is used as a key to the SharedPreferences or PreferenceDataStore.

void
setLayoutResource(int layoutResId)

Sets the layout resource that is inflated as the View to be shown for this preference.

void

Sets the callback to be invoked when this preference is changed by the user (but before the internal state has been updated).

void

Sets the callback to be invoked when this preference is clicked.

void
setOrder(int order)

Sets the order of this preference with respect to other preference objects on the same level.

void
setPersistent(boolean persistent)

Sets whether this preference is persistent.

void

Sets a PreferenceDataStore to be used by this preference instead of using SharedPreferences.

void
setSelectable(boolean selectable)

Sets whether this preference is selectable.

void
setShouldDisableView(boolean shouldDisableView)

Sets whether this preference should disable its view when it gets disabled.

void
setSingleLineTitle(boolean singleLineTitle)

Sets whether to constrain the title of this preference to a single line instead of letting it wrap onto multiple lines.

void

Sets the summary for this preference with a CharSequence.

void
setSummary(int summaryResId)

Sets the summary for this preference with a resource ID.

final void

Set a SummaryProvider that will be invoked whenever the summary of this preference is requested.

void

Sets the title for this preference with a CharSequence.

void
setTitle(int titleResId)

Sets the title for this preference with a resource ID.

void
setViewId(int viewId)

Set the ID that will be assigned to the overall View representing this preference, once bound.

final void
setVisible(boolean visible)

Sets whether this preference should be visible to the user.

void
setWidgetLayoutResource(int widgetLayoutResId)

Sets the layout for the controllable widget portion of this preference.

boolean

Checks whether this preference's dependents should currently be disabled.

@NonNull String

Protected methods

@Nullable T

Finds a preference in the entire hierarchy (above or below this preference) with the given key.

boolean
getPersistedBoolean(boolean defaultReturnValue)

Attempts to get a persisted Boolean if this preference is persistent.

float
getPersistedFloat(float defaultReturnValue)

Attempts to get a persisted Float if this preference is persistent.

int
getPersistedInt(int defaultReturnValue)

Attempts to get a persisted Integer if this preference is persistent.

long
getPersistedLong(long defaultReturnValue)

Attempts to get a persisted Long if this preference is persistent.

String
getPersistedString(String defaultReturnValue)

Attempts to get a persisted set of Strings if this preference is persistent.

void

Should be called when the data of this Preference has changed.

void

Should be called when a preference has been added/removed from this group, or the ordering should be re-evaluated.

void

Called when this preference has been attached to a preference hierarchy.

void

Processes a click on the preference.

@Nullable Object

Called when a preference is being inflated and the default value attribute needs to be read.

void

Called when this preference is being removed from the hierarchy.

void

Hook allowing a preference to re-apply a representation of its internal state that had previously been generated by onSaveInstanceState.

@Nullable Parcelable

Hook allowing a preference to generate a representation of its internal state that can later be used to create a new instance with that same state.

void

Implement this to set the initial value of the preference.

void
onSetInitialValue(boolean restorePersistedValue, Object defaultValue)

This method is deprecated.

Use onSetInitialValue instead.

boolean
persistBoolean(boolean value)

Attempts to persist a Boolean if this preference is persistent.

boolean
persistFloat(float value)

Attempts to persist a Float if this preference is persistent.

boolean
persistInt(int value)

Attempts to persist an Integer if this preference is persistent.

boolean
persistLong(long value)

Attempts to persist a Long if this preference is persistent.

boolean

Attempts to persist a String if this preference is persistent.

boolean

Checks whether, at the given time this method is called, this preference should store/restore its value(s) into the SharedPreferences or into PreferenceDataStore if assigned.

Constants

DEFAULT_ORDER

Added in 1.0.0
public static final int DEFAULT_ORDER = 2147483647

Specify for setOrder if a specific order is not required.

Public constructors

Preference

Added in 1.0.0
public Preference(@NonNull Context context)

Constructor to create a preference.

Parameters
@NonNull Context context

The Context this is associated with, through which it can access the current theme, resources, SharedPreferences, etc.

Preference

Added in 1.0.0
public Preference(@NonNull Context context, @Nullable AttributeSet attrs)

Constructor that is called when inflating a preference from XML. This is called when a preference is being constructed from an XML file, supplying attributes that were specified in the XML file. This version uses a default style of 0, so the only attribute values applied are those in the Context's Theme and the given AttributeSet.

Parameters
@NonNull Context context

The Context this is associated with, through which it can access the current theme, resources, SharedPreferences, etc.

@Nullable AttributeSet attrs

The attributes of the XML tag that is inflating the preference

See also
Preference

Preference

Added in 1.0.0
public Preference(
    @NonNull Context context,
    @Nullable AttributeSet attrs,
    int defStyleAttr
)

Perform inflation from XML and apply a class-specific base style. This constructor allows subclasses to use their own base style when they are inflating. For example, a CheckBoxPreference constructor calls this version of the super class constructor and supplies android.R.attr.checkBoxPreferenceStyle for defStyleAttr. This allows the theme's checkbox preference style to modify all of the base preference attributes as well as the CheckBoxPreference class's attributes.

Parameters
@NonNull Context context

The Context this is associated with, through which it can access the current theme, resources, SharedPreferences, etc.

@Nullable AttributeSet attrs

The attributes of the XML tag that is inflating the preference

int defStyleAttr

An attribute in the current theme that contains a reference to a style resource that supplies default values for the view. Can be 0 to not look for defaults.

See also
Preference

Preference

Added in 1.0.0
public Preference(
    @NonNull Context context,
    @Nullable AttributeSet attrs,
    int defStyleAttr,
    int defStyleRes
)

Perform inflation from XML and apply a class-specific base style. This constructor allows subclasses to use their own base style when they are inflating. For example, a CheckBoxPreference constructor calls this version of the super class constructor and supplies android.R.attr.checkBoxPreferenceStyle for defStyleAttr. This allows the theme's checkbox preference style to modify all of the base preference attributes as well as the CheckBoxPreference class's attributes.

Parameters
@NonNull Context context

The Context this is associated with, through which it can access the current theme, resources, SharedPreferences, etc.

@Nullable AttributeSet attrs

The attributes of the XML tag that is inflating the preference

int defStyleAttr

An attribute in the current theme that contains a reference to a style resource that supplies default values for the view. Can be 0 to not look for defaults.

int defStyleRes

A resource identifier of a style resource that supplies default values for the view, used only if defStyleAttr is 0 or can not be found in the theme. Can be 0 to not look for defaults.

See also
Preference

Public methods

callChangeListener

Added in 1.0.0
public boolean callChangeListener(Object newValue)

Call this method after the user changes the preference, but before the internal state is set. This allows the client to ignore the user value.

Parameters
Object newValue

The new value of this preference

Returns
boolean

true if the user value should be set as the preference value (and persisted)

compareTo

Added in 1.0.0
public int compareTo(@NonNull Preference another)

Compares preference objects based on order (if set), otherwise alphabetically on the titles.

Parameters
@NonNull Preference another

The preference to compare to this one

Returns
int

0 if the same; less than 0 if this preference sorts ahead of another; greater than 0 if this preference sorts after another.

getContext

Added in 1.0.0
public @NonNull Context getContext()

Returns the Context of this preference. Each preference in a preference hierarchy can be from different Context (for example, if multiple activities provide preferences into a single PreferenceFragmentCompat). This Context will be used to save the preference values.

Returns
@NonNull Context

The Context of this preference

getDependency

Added in 1.0.0
public @Nullable String getDependency()

Returns the key of the dependency on this preference.

Returns
@Nullable String

The key of the dependency

See also
setDependency

getExtras

Added in 1.0.0
public @NonNull Bundle getExtras()

Return the extras Bundle object associated with this preference, creating a new Bundle if there currently isn't one. You can use this to get and set individual extra key/value pairs.

getFragment

Added in 1.0.0
public @Nullable String getFragment()

Return the fragment class name associated with this preference.

Returns
@Nullable String

The fragment class name last set via setFragment or XML

getIcon

Added in 1.0.0
public @Nullable Drawable getIcon()

Returns the icon of this preference.

Returns
@Nullable Drawable

The icon

See also
setIcon

getIntent

Added in 1.0.0
public @Nullable Intent getIntent()

Return the Intent associated with this preference.

Returns
@Nullable Intent

The Intent last set via setIntent or XML

getKey

Added in 1.0.0
public String getKey()

Gets the key for this preference, which is also the key used for storing values into SharedPreferences or PreferenceDataStore.

Returns
String

The key

getLayoutResource

Added in 1.0.0
public final int getLayoutResource()

Gets the layout resource that will be shown as the View for this preference.

Returns
int

The layout resource ID

getOnPreferenceChangeListener

Added in 1.0.0
public @Nullable Preference.OnPreferenceChangeListener getOnPreferenceChangeListener()

Returns the callback to be invoked when this preference is changed by the user (but before the internal state has been updated).

Returns
@Nullable Preference.OnPreferenceChangeListener

The callback to be invoked

getOnPreferenceClickListener

Added in 1.0.0
public @Nullable Preference.OnPreferenceClickListener getOnPreferenceClickListener()

Returns the callback to be invoked when this preference is clicked.

Returns
@Nullable Preference.OnPreferenceClickListener

The callback to be invoked

getOrder

Added in 1.0.0
public int getOrder()

Gets the order of this preference with respect to other preference objects on the same level.

Returns
int

The order of this preference

See also
setOrder

getParent

Added in 1.0.0
public @Nullable PreferenceGroup getParent()

Returns the PreferenceGroup which is this preference assigned to or null if this preference is not assigned to any group or is a root preference.

Returns
@Nullable PreferenceGroup

The parent PreferenceGroup or null if not attached to any

getPersistedStringSet

Added in 1.0.0
public Set<StringgetPersistedStringSet(Set<String> defaultReturnValue)

Attempts to get a persisted set of Strings if this preference is persistent.

Parameters
Set<String> defaultReturnValue

The default value to return if either this preference is not persistent or this preference is not present.

Returns
Set<String>

The value from the storage or the default return value

See also
persistStringSet

getPreferenceDataStore

Added in 1.0.0
public @Nullable PreferenceDataStore getPreferenceDataStore()

Returns PreferenceDataStore used by this preference. Returns null if SharedPreferences is used instead.

By default preferences always use SharedPreferences. To make this preference to use the PreferenceDataStore you need to assign your implementation to the preference itself via setPreferenceDataStore or to its PreferenceManager via setPreferenceDataStore.

Returns
@Nullable PreferenceDataStore

The PreferenceDataStore used by this preference or null if none

getPreferenceManager

Added in 1.0.0
public PreferenceManager getPreferenceManager()

Gets the PreferenceManager that manages this preference object's tree.

getSharedPreferences

Added in 1.0.0
public @Nullable SharedPreferences getSharedPreferences()

Returns the SharedPreferences where this preference can read its value(s). Usually, it's easier to use one of the helper read methods: getPersistedBoolean, getPersistedFloat, getPersistedInt, getPersistedLong, getPersistedString.

Returns
@Nullable SharedPreferences

The SharedPreferences where this preference reads its value(s). If this preference is not attached to a preference hierarchy or if a PreferenceDataStore has been set, this method returns null.

getShouldDisableView

Added in 1.0.0
public boolean getShouldDisableView()

Checks whether this preference should disable its view when it's action is disabled.

Returns
boolean

true if it should disable the view

getSummary

Added in 1.0.0
public @Nullable CharSequence getSummary()

Returns the summary of this preference. If a SummaryProvider has been set for this preference, it will be used to provide the summary returned by this method.

Returns
@Nullable CharSequence

The summary

getSummaryProvider

Added in 1.1.0
public final @Nullable Preference.SummaryProvider getSummaryProvider()

Returns the SummaryProvider used to configure the summary of this preference.

Returns
@Nullable Preference.SummaryProvider

The SummaryProvider used to configure the summary of this preference, or null if there is no SummaryProvider set

getTitle

Added in 1.0.0
public @Nullable CharSequence getTitle()

Returns the title of this preference.

Returns
@Nullable CharSequence

The title

See also
setTitle

getWidgetLayoutResource

Added in 1.0.0
public final int getWidgetLayoutResource()

Gets the layout resource for the controllable widget portion of this preference.

Returns
int

The layout resource ID

hasKey

Added in 1.0.0
public boolean hasKey()

Checks whether this preference has a valid key.

Returns
boolean

true if the key exists and is not a blank string, false otherwise

isCopyingEnabled

Added in 1.1.0
public boolean isCopyingEnabled()

Returns whether the summary of this preference can be copied to the clipboard by long pressing on the preference.

Returns
boolean

true if copying is enabled, false otherwise

isEnabled

Added in 1.0.0
public boolean isEnabled()

Checks whether this preference should be enabled in the list.

Returns
boolean

true if this preference is enabled, false otherwise

isIconSpaceReserved

Added in 1.0.0
public boolean isIconSpaceReserved()

Returns whether the space of this preference icon view is reserved.

Returns
boolean

true if the space of this preference icon view is reserved iconSpaceReserved

isPersistent

Added in 1.0.0
public boolean isPersistent()

Checks whether this preference is persistent. If it is, it stores its value(s) into the persistent SharedPreferences storage by default or into PreferenceDataStore if assigned.

Returns
boolean

true if persistent

isSelectable

Added in 1.0.0
public boolean isSelectable()

Checks whether this preference should be selectable in the list.

Returns
boolean

true if it is selectable, false otherwise

isShown

Added in 1.0.0
public final boolean isShown()

Checks whether this preference is shown to the user in the hierarchy. For a preference to be shown in the hierarchy, it and all of its ancestors must be visible and attached to the root PreferenceScreen.

Returns
boolean

true if this preference is shown to the user in the hierarchy

isSingleLineTitle

Added in 1.0.0
public boolean isSingleLineTitle()

Gets whether the title of this preference is constrained to a single line.

Returns
boolean

true if the title of this preference is constrained to a single line singleLineTitle

isVisible

Added in 1.0.0
public final boolean isVisible()

Checks whether this preference should be visible to the user. If this preference is visible, but one or more of its ancestors are not visible, then this preference will not be shown until its ancestors are all visible.

Returns
boolean

true if this preference should be displayed

See also
setVisible
isShown

notifyDependencyChange

Added in 1.0.0
public void notifyDependencyChange(boolean disableDependents)

Notifies any listening dependents of a change that affects the dependency.

Parameters
boolean disableDependents

Whether this preference should disable its dependents.

onAttached

Added in 1.0.0
public void onAttached()

Called when the preference hierarchy has been attached to the list of preferences. This can also be called when this preference has been attached to a group that was already attached to the list of preferences.

onBindViewHolder

Added in 1.0.0
public void onBindViewHolder(@NonNull PreferenceViewHolder holder)

Binds the created View to the data for this preference.

This is a good place to grab references to custom Views in the layout and set properties on them.

Make sure to call through to the superclass's implementation.

Parameters
@NonNull PreferenceViewHolder holder

The ViewHolder that provides references to the views to fill in. These views will be recycled, so you should not hold a reference to them after this method returns.

onDependencyChanged

Added in 1.0.0
public void onDependencyChanged(
    @NonNull Preference dependency,
    boolean disableDependent
)

Called when the dependency changes.

Parameters
@NonNull Preference dependency

The preference that this preference depends on

boolean disableDependent

Set true to disable this preference

onDetached

Added in 1.0.0
public void onDetached()

Called when the preference hierarchy has been detached from the list of preferences. This can also be called when this preference has been removed from a group that was attached to the list of preferences.

onInitializeAccessibilityNodeInfo

Added in 1.0.0
Deprecated in 1.1.0
@CallSuper
public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfoCompat info)

Initializes an android.view.accessibility.AccessibilityNodeInfo with information about the View for this preference.

onParentChanged

Added in 1.0.0
public void onParentChanged(@NonNull Preference parent, boolean disableChild)

Called when the implicit parent dependency changes.