public class

ListPreference

extends DialogPreference

 java.lang.Object

androidx.preference.Preference

androidx.preference.DialogPreference

↳androidx.preference.ListPreference

Subclasses:

DropDownPreference

Gradle dependencies

compile group: 'androidx.preference', name: 'preference', version: '1.2.0'

  • groupId: androidx.preference
  • artifactId: preference
  • version: 1.2.0

Artifact androidx.preference:preference:1.2.0 it located at Google repository (https://maven.google.com/)

Androidx artifact mapping:

androidx.preference:preference com.android.support:preference-v7

Androidx class mapping:

androidx.preference.ListPreference android.support.v7.preference.ListPreference

Overview

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

This preference saves a string value. This string will be the value from the ListPreference.setEntryValues(CharSequence[]) array.

Summary

Fields
from PreferenceDEFAULT_ORDER
Constructors
publicListPreference(Context context)

publicListPreference(Context context, AttributeSet attrs)

publicListPreference(Context context, AttributeSet attrs, int defStyleAttr)

publicListPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)

Methods
public intfindIndexOfValue(java.lang.String value)

Returns the index of the given value (in the entry values array).

public java.lang.CharSequencegetEntries()

The list of entries to be shown in the list in subsequent dialogs.

public java.lang.CharSequencegetEntry()

Returns the entry corresponding to the current value.

public java.lang.CharSequencegetEntryValues()

Returns the array of values to be saved for the preference.

public java.lang.CharSequencegetSummary()

Returns the summary of this preference.

public java.lang.StringgetValue()

Returns the value of the key.

protected java.lang.ObjectonGetDefaultValue(TypedArray a, int index)

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

protected voidonRestoreInstanceState(Parcelable state)

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

protected ParcelableonSaveInstanceState()

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.

protected voidonSetInitialValue(java.lang.Object defaultValue)

Implement this to set the initial value of the preference.

public voidsetEntries(java.lang.CharSequence entries[])

Sets the human-readable entries to be shown in the list.

public voidsetEntries(int entriesResId)

public voidsetEntryValues(java.lang.CharSequence entryValues[])

The array to find the value to save for a preference when an entry from entries is selected.

public voidsetEntryValues(int entryValuesResId)

public voidsetSummary(java.lang.CharSequence summary)

Sets the summary for this preference with a CharSequence.

public voidsetValue(java.lang.String value)

Sets the value of the key.

public voidsetValueIndex(int index)

Sets the value to the given index from the entry values.

from DialogPreferencegetDialogIcon, getDialogLayoutResource, getDialogMessage, getDialogTitle, getNegativeButtonText, getPositiveButtonText, onClick, setDialogIcon, setDialogLayoutResource, setDialogMessage, setDialogMessage, setDialogTitle, setDialogTitle, setNegativeButtonText, setNegativeButtonText, setPositiveButtonText, setPositiveButtonText
from PreferencecallChangeListener, compareTo, findPreferenceInHierarchy, getContext, getDependency, getExtras, getFragment, getIcon, getIntent, getKey, getLayoutResource, getOnPreferenceChangeListener, getOnPreferenceClickListener, getOrder, getParent, getPersistedBoolean, getPersistedFloat, getPersistedInt, getPersistedLong, getPersistedString, getPersistedStringSet, getPreferenceDataStore, getPreferenceManager, getSharedPreferences, getShouldDisableView, getSummaryProvider, getTitle, getWidgetLayoutResource, hasKey, isCopyingEnabled, isEnabled, isIconSpaceReserved, isPersistent, isSelectable, isShown, isSingleLineTitle, isVisible, notifyChanged, notifyDependencyChange, notifyHierarchyChanged, onAttached, onAttachedToHierarchy, onAttachedToHierarchy, onBindViewHolder, onDependencyChanged, onDetached, onInitializeAccessibilityNodeInfo, onParentChanged, onPrepareForRemoval, onSetInitialValue, peekExtras, performClick, performClick, persistBoolean, persistFloat, persistInt, persistLong, persistString, persistStringSet, restoreHierarchyState, saveHierarchyState, setCopyingEnabled, setDefaultValue, setDependency, setEnabled, setFragment, setIcon, setIconSpaceReserved, setIntent, setKey, setLayoutResource, setOnPreferenceChangeListener, setOnPreferenceClickListener, setOrder, setPersistent, setPreferenceDataStore, setSelectable, setShouldDisableView, setSingleLineTitle, setSummary, setSummaryProvider, setTitle, setTitle, setViewId, setVisible, setWidgetLayoutResource, shouldDisableDependents, shouldPersist, toString
from java.lang.Objectclone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructors

public ListPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)

public ListPreference(Context context, AttributeSet attrs, int defStyleAttr)

public ListPreference(Context context, AttributeSet attrs)

public ListPreference(Context context)

Methods

public void setEntries(java.lang.CharSequence entries[])

Sets the human-readable entries to be shown in the list. This will be shown in subsequent dialogs.

Each entry must have a corresponding index in ListPreference.setEntryValues(CharSequence[]).

Parameters:

entries: The entries

See also: ListPreference.setEntryValues(CharSequence[])

public void setEntries(int entriesResId)

Parameters:

entriesResId: The entries array as a resource

See also: ListPreference.setEntries(CharSequence[])

public java.lang.CharSequence getEntries()

The list of entries to be shown in the list in subsequent dialogs.

Returns:

The list as an array

public void setEntryValues(java.lang.CharSequence entryValues[])

The array to find the value to save for a preference when an entry from entries is selected. If a user clicks on the second item in entries, the second item in this array will be saved to the preference.

Parameters:

entryValues: The array to be used as values to save for the preference

public void setEntryValues(int entryValuesResId)

Parameters:

entryValuesResId: The entry values array as a resource

See also: ListPreference.setEntryValues(CharSequence[])

public java.lang.CharSequence getEntryValues()

Returns the array of values to be saved for the preference.

Returns:

The array of values

public void setSummary(java.lang.CharSequence summary)

Sets the summary for this preference with a CharSequence.

You can also use a Preference.SummaryProvider to dynamically configure the summary of this preference.

Parameters:

summary: The summary for the preference

See also: Preference.setSummaryProvider(Preference.SummaryProvider)

public java.lang.CharSequence getSummary()

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

Returns:

The summary

See also: Preference.setSummary(CharSequence), Preference.setSummaryProvider(Preference.SummaryProvider)

public void setValue(java.lang.String value)

Sets the value of the key. This should be one of the entries in ListPreference.getEntryValues().

Parameters:

value: The value to set for the key

public java.lang.String getValue()

Returns the value of the key. This should be one of the entries in ListPreference.getEntryValues().

Returns:

The value of the key

public java.lang.CharSequence getEntry()

Returns the entry corresponding to the current value.

Returns:

The entry corresponding to the current value, or null

public int findIndexOfValue(java.lang.String value)

Returns the index of the given value (in the entry values array).

Parameters:

value: The value whose index should be returned

Returns:

The index of the value, or -1 if not found

public void setValueIndex(int index)

Sets the value to the given index from the entry values.

Parameters:

index: The index of the value to set

protected java.lang.Object onGetDefaultValue(TypedArray a, int index)

Called when a preference is being inflated and the default value attribute needs to be read. Since different preference types have different value types, the subclass should get and return the default value which will be its value type.

For example, if the value type is String, the body of the method would proxy to .

Parameters:

a: The set of attributes
index: The index of the default value attribute

Returns:

The default value of this preference type

protected void onSetInitialValue(java.lang.Object defaultValue)

Implement this to set the initial value of the preference.

If you are persisting values to SharedPreferences or a PreferenceDataStore you should restore the saved value for the preference.

If you are not persisting values, or there is no value saved for the preference, you should set the value of the preference to defaultValue.

Parameters:

defaultValue: The default value for the preference if set, otherwise null.

protected Parcelable onSaveInstanceState()

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. This state should only contain information that is not persistent or can be reconstructed later.

Returns:

A Parcelable object containing the current dynamic state of this preference, or null if there is nothing interesting to save. The default implementation returns null.

See also: Preference.onRestoreInstanceState(Parcelable), Preference.saveHierarchyState(Bundle)

protected void onRestoreInstanceState(Parcelable state)

Hook allowing a preference to re-apply a representation of its internal state that had previously been generated by Preference.onSaveInstanceState(). This function will never be called with a null state.

Parameters:

state: The saved state that had previously been returned by Preference.onSaveInstanceState().

See also: Preference.onSaveInstanceState(), Preference.restoreHierarchyState(Bundle)

Source

/*
 * Copyright 2018 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package androidx.preference;

import android.content.Context;
import android.content.res.TypedArray;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;

import androidx.annotation.ArrayRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.res.TypedArrayUtils;

/**
 * A {@link Preference} that displays a list of entries as a dialog.
 *
 * <p>This preference saves a string value. This string will be the value from the
 * {@link #setEntryValues(CharSequence[])} array.
 *
 * @attr name android:entries
 * @attr name android:entryValues
 */
public class ListPreference extends DialogPreference {
    private static final String TAG = "ListPreference";
    private CharSequence[] mEntries;
    private CharSequence[] mEntryValues;
    private String mValue;
    private String mSummary;
    private boolean mValueSet;

    public ListPreference(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr,
            int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);

        TypedArray a = context.obtainStyledAttributes(
                attrs, R.styleable.ListPreference, defStyleAttr, defStyleRes);

        mEntries = TypedArrayUtils.getTextArray(a, R.styleable.ListPreference_entries,
                R.styleable.ListPreference_android_entries);

        mEntryValues = TypedArrayUtils.getTextArray(a, R.styleable.ListPreference_entryValues,
                R.styleable.ListPreference_android_entryValues);

        if (TypedArrayUtils.getBoolean(a, R.styleable.ListPreference_useSimpleSummaryProvider,
                R.styleable.ListPreference_useSimpleSummaryProvider, false)) {
            setSummaryProvider(SimpleSummaryProvider.getInstance());
        }

        a.recycle();

        //Retrieve the Preference summary attribute since it's private in the Preference class.
        a = context.obtainStyledAttributes(attrs,
                R.styleable.Preference, defStyleAttr, defStyleRes);

        mSummary = TypedArrayUtils.getString(a, R.styleable.Preference_summary,
                R.styleable.Preference_android_summary);

        a.recycle();
    }

    public ListPreference(@NonNull Context context, @Nullable AttributeSet attrs,
            int defStyleAttr) {
        this(context, attrs, defStyleAttr, 0);
    }

    public ListPreference(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, TypedArrayUtils.getAttr(context, R.attr.dialogPreferenceStyle,
                android.R.attr.dialogPreferenceStyle));
    }

    public ListPreference(@NonNull Context context) {
        this(context, null);
    }

    /**
     * Sets the human-readable entries to be shown in the list. This will be shown in subsequent
     * dialogs.
     *
     * <p>Each entry must have a corresponding index in {@link #setEntryValues(CharSequence[])}.
     *
     * @param entries The entries
     * @see #setEntryValues(CharSequence[])
     */
    public void setEntries(CharSequence[] entries) {
        mEntries = entries;
    }

    /**
     * @param entriesResId The entries array as a resource
     * @see #setEntries(CharSequence[])
     */
    public void setEntries(@ArrayRes int entriesResId) {
        setEntries(getContext().getResources().getTextArray(entriesResId));
    }

    /**
     * The list of entries to be shown in the list in subsequent dialogs.
     *
     * @return The list as an array
     */
    public CharSequence[] getEntries() {
        return mEntries;
    }

    /**
     * The array to find the value to save for a preference when an entry from entries is
     * selected. If a user clicks on the second item in entries, the second item in this array
     * will be saved to the preference.
     *
     * @param entryValues The array to be used as values to save for the preference
     */
    public void setEntryValues(CharSequence[] entryValues) {
        mEntryValues = entryValues;
    }

    /**
     * @param entryValuesResId The entry values array as a resource
     * @see #setEntryValues(CharSequence[])
     */
    public void setEntryValues(@ArrayRes int entryValuesResId) {
        setEntryValues(getContext().getResources().getTextArray(entryValuesResId));
    }

    /**
     * Returns the array of values to be saved for the preference.
     *
     * @return The array of values
     */
    public CharSequence[] getEntryValues() {
        return mEntryValues;
    }

    @Override
    public void setSummary(@Nullable CharSequence summary) {
        super.setSummary(summary);
        if (summary == null) {
            mSummary = null;
        } else {
            mSummary = summary.toString();
        }
    }

    @SuppressWarnings("unchecked")
    @Nullable
    @Override
    public CharSequence getSummary() {
        if (getSummaryProvider() != null) {
            return getSummaryProvider().provideSummary(this);
        }
        final CharSequence entry = getEntry();
        CharSequence summary = super.getSummary();
        if (mSummary == null) {
            return summary;
        }
        String formattedString = String.format(mSummary, entry == null ? "" : entry);
        if (TextUtils.equals(formattedString, summary)) {
            return summary;
        }
        Log.w(TAG,
                "Setting a summary with a String formatting marker is no longer supported."
                        + " You should use a SummaryProvider instead.");
        return formattedString;
    }

    /**
     * Sets the value of the key. This should be one of the entries in {@link #getEntryValues()}.
     *
     * @param value The value to set for the key
     */
    public void setValue(String value) {
        // Always persist/notify the first time.
        final boolean changed = !TextUtils.equals(mValue, value);
        if (changed || !mValueSet) {
            mValue = value;
            mValueSet = true;
            persistString(value);
            if (changed) {
                notifyChanged();
            }
        }
    }

    /**
     * Returns the value of the key. This should be one of the entries in {@link #getEntryValues()}.
     *
     * @return The value of the key
     */
    public String getValue() {
        return mValue;
    }

    /**
     * Returns the entry corresponding to the current value.
     *
     * @return The entry corresponding to the current value, or {@code null}
     */
    @Nullable
    public CharSequence getEntry() {
        int index = getValueIndex();
        return index >= 0 && mEntries != null ? mEntries[index] : null;
    }

    /**
     * Returns the index of the given value (in the entry values array).
     *
     * @param value The value whose index should be returned
     * @return The index of the value, or -1 if not found
     */
    public int findIndexOfValue(String value) {
        if (value != null && mEntryValues != null) {
            for (int i = mEntryValues.length - 1; i >= 0; i--) {
                if (TextUtils.equals(mEntryValues[i].toString(), value)) {
                    return i;
                }
            }
        }
        return -1;
    }

    /**
     * Sets the value to the given index from the entry values.
     *
     * @param index The index of the value to set
     */
    public void setValueIndex(int index) {
        if (mEntryValues != null) {
            setValue(mEntryValues[index].toString());
        }
    }

    private int getValueIndex() {
        return findIndexOfValue(mValue);
    }

    @Override
    protected Object onGetDefaultValue(@NonNull TypedArray a, int index) {
        return a.getString(index);
    }

    @Override
    protected void onSetInitialValue(Object defaultValue) {
        setValue(getPersistedString((String) defaultValue));
    }

    @Nullable
    @Override
    protected Parcelable onSaveInstanceState() {
        final Parcelable superState = super.onSaveInstanceState();
        if (isPersistent()) {
            // No need to save instance state since it's persistent
            return superState;
        }

        final SavedState myState = new SavedState(superState);
        myState.mValue = getValue();
        return myState;
    }

    @Override
    protected void onRestoreInstanceState(@Nullable Parcelable state) {
        if (state == null || !state.getClass().equals(SavedState.class)) {
            // Didn't save state for us in onSaveInstanceState
            super.onRestoreInstanceState(state);
            return;
        }

        SavedState myState = (SavedState) state;
        super.onRestoreInstanceState(myState.getSuperState());
        setValue(myState.mValue);
    }

    private static class SavedState extends BaseSavedState {
        public static final Parcelable.Creator<SavedState> CREATOR =
                new Parcelable.Creator<SavedState>() {
                    @Override
                    public SavedState createFromParcel(Parcel in) {
                        return new SavedState(in);
                    }

                    @Override
                    public SavedState[] newArray(int size) {
                        return new SavedState[size];
                    }
                };

        String mValue;

        SavedState(Parcel source) {
            super(source);
            mValue = source.readString();
        }

        SavedState(Parcelable superState) {
            super(superState);
        }

        @Override
        public void writeToParcel(@NonNull Parcel dest, int flags) {
            super.writeToParcel(dest, flags);
            dest.writeString(mValue);
        }
    }

    /**
     * A simple {@link androidx.preference.Preference.SummaryProvider} implementation for a
     * {@link ListPreference}. If no value has been set, the summary displayed will be 'Not set',
     * otherwise the summary displayed will be the entry set for this preference.
     */
    public static final class SimpleSummaryProvider implements SummaryProvider<ListPreference> {

        private static SimpleSummaryProvider sSimpleSummaryProvider;

        private SimpleSummaryProvider() {}

        /**
         * Retrieve a singleton instance of this simple
         * {@link androidx.preference.Preference.SummaryProvider} implementation.
         *
         * @return a singleton instance of this simple
         * {@link androidx.preference.Preference.SummaryProvider} implementation
         */
        @NonNull
        public static SimpleSummaryProvider getInstance() {
            if (sSimpleSummaryProvider == null) {
                sSimpleSummaryProvider = new SimpleSummaryProvider();
            }
            return sSimpleSummaryProvider;
        }

        @Nullable
        @Override
        public CharSequence provideSummary(@NonNull ListPreference preference) {
            if (TextUtils.isEmpty(preference.getEntry())) {
                return (preference.getContext().getString(R.string.not_set));
            } else {
                return preference.getEntry();
            }
        }
    }
}