public class

DropDownPreference

extends ListPreference

 java.lang.Object

androidx.preference.Preference

androidx.preference.DialogPreference

androidx.preference.ListPreference

↳androidx.preference.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.DropDownPreference android.support.v7.preference.DropDownPreference

Overview

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

Summary

Fields
from PreferenceDEFAULT_ORDER
Constructors
publicDropDownPreference(Context context)

publicDropDownPreference(Context context, AttributeSet attrs)

publicDropDownPreference(Context context, AttributeSet attrs, int defStyle)

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

Methods
protected ArrayAdaptercreateAdapter()

By default, this class uses a simple .

protected voidnotifyChanged()

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

public voidonBindViewHolder(PreferenceViewHolder holder)

Binds the created View to the data for this preference.

protected voidonClick()

Processes a click on the preference.

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

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

public voidsetValueIndex(int index)

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

from ListPreferencefindIndexOfValue, getEntries, getEntry, getEntryValues, getSummary, getValue, onGetDefaultValue, onRestoreInstanceState, onSaveInstanceState, onSetInitialValue, setEntries, setEntryValues, setEntryValues, setSummary, setValue
from DialogPreferencegetDialogIcon, getDialogLayoutResource, getDialogMessage, getDialogTitle, getNegativeButtonText, getPositiveButtonText, 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, notifyDependencyChange, notifyHierarchyChanged, onAttached, onAttachedToHierarchy, onAttachedToHierarchy, 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 DropDownPreference(Context context)

public DropDownPreference(Context context, AttributeSet attrs)

public DropDownPreference(Context context, AttributeSet attrs, int defStyle)

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

Methods

protected void onClick()

Processes a click on the preference. This includes saving the value to the SharedPreferences. However, the overridden method should call Preference.callChangeListener(Object) to make sure the client wants to update the preference's state with the new value.

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[])

protected ArrayAdapter createAdapter()

By default, this class uses a simple . But if you need a more complicated adapter, this method can be overridden to create a custom one.

Note: This method is called from the constructor. Overridden methods will get called before any subclass initialization.

Returns:

The custom that needs to be used with this class

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 void notifyChanged()

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

public void onBindViewHolder(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:

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.

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.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * A {@link ListPreference} that presents the options in a drop down menu rather than a dialog.
 */
public class DropDownPreference extends ListPreference {

    private final Context mContext;
    private final ArrayAdapter mAdapter;

    private Spinner mSpinner;

    private final OnItemSelectedListener mItemSelectedListener = new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
            if (position >= 0) {
                String value = getEntryValues()[position].toString();
                if (!value.equals(getValue()) && callChangeListener(value)) {
                    setValue(value);
                }
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            // noop
        }
    };

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

    public DropDownPreference(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, R.attr.dropdownPreferenceStyle);
    }

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

    public DropDownPreference(@NonNull Context context, @Nullable AttributeSet attrs,
            int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        mContext = context;
        mAdapter = createAdapter();

        updateEntries();
    }

    @Override
    protected void onClick() {
        mSpinner.performClick();
    }

    @Override
    public void setEntries(@NonNull CharSequence[] entries) {
        super.setEntries(entries);
        updateEntries();
    }

    /**
     * By default, this class uses a simple {@link ArrayAdapter}. But if you need a more
     * complicated adapter, this method can be overridden to create a custom one.
     *
     * <p>Note: This method is called from the constructor. Overridden methods will get called
     * before any subclass initialization.
     *
     * @return The custom {@link ArrayAdapter} that needs to be used with this class
     */
    @NonNull
    protected ArrayAdapter createAdapter() {
        return new ArrayAdapter<>(mContext, android.R.layout.simple_spinner_dropdown_item);
    }

    @SuppressWarnings("unchecked")
    private void updateEntries() {
        mAdapter.clear();
        if (getEntries() != null) {
            for (CharSequence c : getEntries()) {
                mAdapter.add(c.toString());
            }
        }
    }

    @Override
    public void setValueIndex(int index) {
        setValue(getEntryValues()[index].toString());
    }

    @Override
    protected void notifyChanged() {
        super.notifyChanged();
        // When setting a SummaryProvider for this Preference, this method may be called before
        // mAdapter has been set in ListPreference's constructor.
        if (mAdapter != null) {
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onBindViewHolder(@NonNull PreferenceViewHolder holder) {
        mSpinner = holder.itemView.findViewById(R.id.spinner);
        mSpinner.setAdapter(mAdapter);
        mSpinner.setOnItemSelectedListener(mItemSelectedListener);
        mSpinner.setSelection(findSpinnerIndexOfValue(getValue()));
        super.onBindViewHolder(holder);
    }

    private int findSpinnerIndexOfValue(String value) {
        CharSequence[] entryValues = getEntryValues();
        if (value != null && entryValues != null) {
            for (int i = entryValues.length - 1; i >= 0; i--) {
                if (TextUtils.equals(entryValues[i].toString(), value)) {
                    return i;
                }
            }
        }
        return Spinner.INVALID_POSITION;
    }
}