public class

EditTextPreference

extends DialogPreference

 java.lang.Object

androidx.preference.Preference

androidx.preference.DialogPreference

↳androidx.preference.EditTextPreference

Gradle dependencies

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

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

Artifact androidx.preference:preference:1.2.1 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.EditTextPreference android.support.v7.preference.EditTextPreference

Overview

A DialogPreference that shows a in the dialog.

This preference saves a string value.

Summary

Fields
from PreferenceDEFAULT_ORDER
Constructors
publicEditTextPreference(Context context)

publicEditTextPreference(Context context, AttributeSet attrs)

publicEditTextPreference(Context context, AttributeSet attrs, int defStyleAttr)

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

Methods
public java.lang.StringgetText()

Gets the text from the current data storage.

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 voidsetOnBindEditTextListener(EditTextPreference.OnBindEditTextListener onBindEditTextListener)

Set an EditTextPreference.OnBindEditTextListener that will be invoked when the corresponding dialog view for this preference is bound.

public voidsetText(java.lang.String text)

Saves the text to the current data storage.

public booleanshouldDisableDependents()

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

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, getSummary, 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, setSummary, setSummaryProvider, setTitle, setTitle, setViewId, setVisible, setWidgetLayoutResource, shouldPersist, toString
from java.lang.Objectclone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructors

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

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

public EditTextPreference(Context context, AttributeSet attrs)

public EditTextPreference(Context context)

Methods

public void setText(java.lang.String text)

Saves the text to the current data storage.

Parameters:

text: The text to save

public java.lang.String getText()

Gets the text from the current data storage.

Returns:

The current preference value

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.

public boolean shouldDisableDependents()

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

Returns:

true if the dependents should be disabled, otherwise false

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)

public void setOnBindEditTextListener(EditTextPreference.OnBindEditTextListener onBindEditTextListener)

Set an EditTextPreference.OnBindEditTextListener that will be invoked when the corresponding dialog view for this preference is bound. Set null to remove the existing OnBindEditTextListener.

Parameters:

onBindEditTextListener: The EditTextPreference.OnBindEditTextListener that will be invoked when the corresponding dialog view for this preference is bound

See also: EditTextPreference.OnBindEditTextListener

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.widget.EditText;

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

/**
 * A {@link DialogPreference} that shows a {@link EditText} in the dialog.
 *
 * <p>This preference saves a string value.
 */
public class EditTextPreference extends DialogPreference {
    private String mText;

    @Nullable
    private OnBindEditTextListener mOnBindEditTextListener;

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

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

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

        a.recycle();
    }

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

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

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

    /**
     * Saves the text to the current data storage.
     *
     * @param text The text to save
     */
    public void setText(@Nullable String text) {
        final boolean wasBlocking = shouldDisableDependents();

        mText = text;

        persistString(text);

        final boolean isBlocking = shouldDisableDependents();
        if (isBlocking != wasBlocking) {
            notifyDependencyChange(isBlocking);
        }

        notifyChanged();
    }

    /**
     * Gets the text from the current data storage.
     *
     * @return The current preference value
     */
    @Nullable
    public String getText() {
        return mText;
    }

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

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

    @Override
    public boolean shouldDisableDependents() {
        return TextUtils.isEmpty(mText) || super.shouldDisableDependents();
    }

    @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.mText = getText();
        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());
        setText(myState.mText);
    }

    /**
     * Set an {@link OnBindEditTextListener} that will be invoked when the corresponding dialog
     * view for this preference is bound. Set {@code null} to remove the existing
     * OnBindEditTextListener.
     *
     * @param onBindEditTextListener The {@link OnBindEditTextListener} that will be invoked when
     *                               the corresponding dialog view for this preference is bound
     * @see OnBindEditTextListener
     */
    public void setOnBindEditTextListener(@Nullable OnBindEditTextListener onBindEditTextListener) {
        mOnBindEditTextListener = onBindEditTextListener;
    }

    /**
     * Returns the {@link OnBindEditTextListener} used to configure the {@link EditText}
     * displayed in the corresponding dialog view for this preference.
     *
     * @return The {@link OnBindEditTextListener} set for this preference, or {@code null} if
     * there is no OnBindEditTextListener set
     * @see OnBindEditTextListener
     */
    @Nullable OnBindEditTextListener getOnBindEditTextListener() {
        return mOnBindEditTextListener;
    }

    /**
     * Interface definition for a callback to be invoked when the corresponding dialog view for
     * this preference is bound. This allows you to customize the {@link EditText} displayed
     * in the dialog, such as setting a max length or a specific input type.
     */
    public interface OnBindEditTextListener {
        /**
         * Called when the dialog view for this preference has been bound, allowing you to
         * customize the {@link EditText} displayed in the dialog.
         *
         * @param editText The {@link EditText} displayed in the dialog
         */
        void onBindEditText(@NonNull EditText editText);
    }

    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 mText;

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

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

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

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

        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 EditTextPreference preference) {
            if (TextUtils.isEmpty(preference.getText())) {
                return (preference.getContext().getString(R.string.not_set));
            } else {
                return preference.getText();
            }
        }
    }

}