Display the value of the EditTextPreference in summary

androidx edittextpreference
edittextpreference custom dialog
exercise 8 4 use an edittextpreference element
androidx preference example
android preferences
preference xml android
androidx preference preferencescreen
android settings activity

I'm a learning how to develop in Android and want to make a setting activity,

My setting activity

public class Main extends Activity  {


    protected SettingsFragment settingsFragment;


    @SuppressLint("NewApi")
    @TargetApi(11)
    public class SettingsFragment extends PreferenceFragment implements
            SharedPreferences.OnSharedPreferenceChangeListener {


        @Override
        public void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.preferences);
            setSummaries();


        }


        @Override
        public void onResume() {
            final SharedPreferences sh = getPreferenceManager().getSharedPreferences() ;
            super.onResume();
            sh.registerOnSharedPreferenceChangeListener(this);

        }

        @Override
        public void onPause() {
            final SharedPreferences sh = getPreferenceManager().getSharedPreferences() ;
            super.onPause();
            sh.unregisterOnSharedPreferenceChangeListener(this);
        }

        @SuppressLint("NewApi")
        public void setSummaries(){

           final SharedPreferences sh = getPreferenceManager().getSharedPreferences() ;


            //Pref1
            Preference stylePref = findPreference("editTextPref");
            stylePref.setSummary(sh.getString("editTextPref", ""));

            //here the other preferences..
        }


        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
            if (key.equals("editTextPref")) {
                Preference pref = settingsFragment.findPreference(key);
                // Set summary to be the user-description for the selected value
                pref.setSummary(sharedPreferences.getString(key, ""));

            }
            //here the others preferences
        }
    }//End fragment

    @SuppressLint("NewApi")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        settingsFragment = new SettingsFragment();
        getFragmentManager().beginTransaction()
                .replace(android.R.id.content, settingsFragment)
                .commit();


    }


}

and my res/preferences.xml file

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <PreferenceCategory
        android:title="BTA"
        xmlns:android="http://schemas.android.com/apk/res/android">


        <EditTextPreference
            android:key="editTextPref"
            android:title="Numero de telephone"
            android:summary="This allows you to enter a string"
            android:defaultValue="*"/>

    </PreferenceCategory>

</PreferenceScreen>

So now i have the activity for the setting activity. But i want to display the value of the EditTextPref in android:summary. I have found many topics but all the functions was deprecated.

EDIT : thanks to @Ace_McIntosh , I edited my code for people who want it, it's working now.

Just use the setSummary method on the desired Preference object. Call it upon resuming your settings fragment for each entry that you wish to update (i.e., all the EditTextPreference entries in your case) and register an OnSharedPreferenceChangeListener on the concrete SharedPreferences object (so that you can update the summary in case it is changed) – and pass it the desired EditTextPreference's value (which you can obtain via its getText() method).

Implement it in your MyPreferenceFragment like this (I don't guarantee that it will work right of the bat, it serves the purpose to just give you an idea):

public class MyPreferenceFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
    SharedPreferences sharedPreferences;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // load the preferences from your XML resource (which I assume you already do anyway)
        addPreferencesFromResource(R.xml.preferences);
    }

    @Override
    public void onResume() {
        super.onResume();

        sharedPreferences = getPreferenceManager().getSharedPreferences();

        // we want to watch the preference values' changes
        sharedPreferences.registerOnSharedPreferenceChangeListener(this);

        Map<String, ?> preferencesMap = sharedPreferences.getAll();
        // iterate through the preference entries and update their summary if they are an instance of EditTextPreference
        for (Map.Entry<String, ?> preferenceEntry : preferencesMap.entrySet()) {
            if (preferenceEntry instanceof EditTextPreference) {
                updateSummary((EditTextPreference) preferenceEntry);
            }
        }
    }

    @Override
    public void onPause() {
        sharedPreferences.unregisterOnSharedPreferenceChangeListener(this);
        super.onPause();
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
                                          String key) {
        Map<String, ?> preferencesMap = sharedPreferences.getAll();

        // get the preference that has been changed
        Object changedPreference = preferencesMap.get(key);
        // and if it's an instance of EditTextPreference class, update its summary
        if (preferencesMap.get(key) instanceof EditTextPreference) {
            updateSummary((EditTextPreference) changedPreference);
        }
    }

    private void updateSummary(EditTextPreference preference) {
        // set the EditTextPreference's summary value to its current text
        preference.setSummary(preference.getText());
    }
}

Android Preference: Show current value in summary, I found that the default preference like EditTextPreference does not show the current value as summary (and no way to make them do it). Home » Android » android – Display the value of the EditTextPreference in summary android – Display the value of the EditTextPreference in summary Posted by: admin May 11, 2020 Leave a comment

Just override getSummary of EditTextPreference, then you will get a EditTextPreference with its value displayed as summary.

public class EditSummaryPreference extends EditTextPreference {
    ...// omit constructor

    @Override
    public CharSequence getSummary() {
        return getText();
    }
}

EditTextPreference, This preference will store a string into the SharedPreferences. See EditText Attributes . Summary. Inherited XML attributes. From class android. I'm a newbie to Android. I'm learning about PreferenceActivity. I need some guidance on How to display current value of EditTextPreference at right side of them. Like this:----- |EditTextPreference value | |"Summary" | ----- This is may code:

(In Kotlin) I would prefer to do something a bit more simple and just create a class which extends the EditTextPreference:

import android.content.Context
import android.support.v7.preference.EditTextPreference
import android.util.AttributeSet

/**
 * This class was created by Anthony M Cannon on 17/04/2018.
 */
class SummarisedEditTextPreference @JvmOverloads constructor(context: Context,
    attrs: AttributeSet? = null) : EditTextPreference(context, attrs) {

    private var mOnChangeListener: OnPreferenceChangeListener? = null

    init {
        super.setOnPreferenceChangeListener { preference, newValue ->
            summary = newValue as String
            mOnChangeListener?.onPreferenceChange(preference, newValue) ?: true
        }
    }

    /**
    * Called when this Preference has been attached to a Preference hierarchy.
    * Make sure to call the super implementation.
    *
    * @param preferenceManager The PreferenceManager of the hierarchy.
    */
    override fun onAttachedToHierarchy(preferenceManager: PreferenceManager) {
        super.onAttachedToHierarchy(preferenceManager)
        summary = sharedPreferences.getString(key, null)
    }


    /**
     * Sets the callback to be invoked when this Preference is changed by the
     * user (but before the internal state has been updated).
     *
     * @param onPreferenceChangeListener The callback to be invoked.
     */
    override fun setOnPreferenceChangeListener(
        onPreferenceChangeListener: OnPreferenceChangeListener) {
        mOnChangeListener = onPreferenceChangeListener
    }
}

You can then use this like so:

<<your package name>.SummarisedEditTextPreference/>

android.preference.EditTextPreference.getText java code examples , Setting UI preference Summary field to the value of the preference String key) { // Update summary value EditTextPreference pref = (EditTextPreference)​findPreference(key); pref. LENGTH_SHORT).show(); if (ruleDownloadUrl.​getText(). 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 TypedArray#getString(int). Unit

There's some bugs in the example posted above so I thought I post a working solution (supports ListPreference and MultiSelectListPreference as well)

public class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {

private SharedPreferences sharedPreferences;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.settings);
}

@Override
public void onResume() {
    super.onResume();

    sharedPreferences = getPreferenceManager().getSharedPreferences();
    sharedPreferences.registerOnSharedPreferenceChangeListener(this);

    PreferenceScreen preferenceScreen = getPreferenceScreen();
    for(int i = 0; i < preferenceScreen.getPreferenceCount(); i++) {
        setSummary(getPreferenceScreen().getPreference(i));
    }
}

@Override
public void onPause() {
    sharedPreferences.unregisterOnSharedPreferenceChangeListener(this);
    super.onPause();
}

@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
    Preference pref = getPreferenceScreen().findPreference(key);
    setSummary(pref);
}

private void setSummary(Preference pref) {
    if (pref instanceof EditTextPreference) {
        updateSummary((EditTextPreference) pref);
    } else if (pref instanceof ListPreference) {
        updateSummary((ListPreference) pref);
    } else if (pref instanceof MultiSelectListPreference) {
        updateSummary((MultiSelectListPreference) pref);
    }
}

private void updateSummary(MultiSelectListPreference pref) {
    pref.setSummary(Arrays.toString(pref.getValues().toArray()));
}

private void updateSummary(ListPreference pref) {
    pref.setSummary(pref.getValue());
}

private void updateSummary(EditTextPreference preference) {
    preference.setSummary(preference.getText());
}
}

EditText Preference Summary, Posts about EditText Preference Summary written by Prashant Thakkar. key and value of the Preferences defined in the preferences screen  Question: Tag: android I'm a newbie to Android. I'm learning about PreferenceActivity. I need some guidance on How to display current value of EditTextPreference at right side of them.

In androidx library, EditTextPreference has app:useSimpleSummaryProvider attribute. Using the attribute you won't need to extend any class or listen any changes on SharedPreferences. You can check the sample code at https://github.com/googlesamples/android-preferences/blob/master/app/src/main/res/xml/dialogs.xml

Change Preference Summary · Prashant Thakkar, First create a preference screen with only one preference EditTextPreference as android:summary="Enter Your Name" android:title="Edit Text Preference" the key and value of the Preferences defined in the preferences screen via xml  Android Platform. API level 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1. Manifest.permission. Manifest.permission_group. android.accessibilityservice. AccessibilityService.MagnificationController.OnMagnificationChangedListener. AccessibilityService.SoftKeyboardController.OnShowModeChangedListener.

Exploring Android Jetpack: Preferences, In order to build a preferences screen, we have what is known as the value; title: The title used for the display of the preference; summary: The to listen for when the dialog for the edit text preference is displayed to the user  More specifically, when the * preference's value is changed, its summary (line of text below the * preference title) is updated to reflect the value. The summary is also * immediately updated upon calling this method. The exact display format is * dependent on the type of preference.

Java Code Examples android.preference.EditTextPreference , getText()); } else { // For all other preferences, set the summary to the value's ListPreference) { // For list preferences, look up the correct display value in // the  In Today’s post we are going to look at How to Change Summary of Edit Text Preference. But before moving ahead, if you want to know more about Preferences click here. First create a preference screen with only one preference EditTextPreference as show below in xml. Let us call this xml as setttings.xml

Android: Display Preference value in Preference screen, to use the summary field in a ListPreference to show its value. This works well. The same technique is also needed for an EditTextPreference,  Android Preference: Show current value in summary Posted on September 29, 2013 by Enzam When creating android preference view, I found that the default preference like EditTextPreference does not show the current value as summary (and no way to make them do it).

Comments
  • Possible duplicate of How do I display the current value of an Android Preference in the Preference summary?
  • the problem is that addPreferencesFromResource is deprecated.
  • It is deprecated only in PreferenceActivity class, you have to call it in the PreferenceFragment class (where it's not deprecated, as you may see in the documentation). Be sure to utilize the fragment (you haven't posted the code of it, I only see that you create a new instance of MyPreferenceFragment in your activity class). Also note that the parent activity of a PreferenceFragment doesn't have to extend PreferenceActivity, it can be just an ordinary activity.
  • You need to register a listener for preference changes via registerOnSharedPreferenceChangeListener method of your SharedPreferences object and handle the update in the listener. There is an example how to do this in the code I posted you, the said listener is the class MyPreferenceFragment itself (it has to implement the appropriate interface) and as you can see it contains the onSharedPreferenceChanged callback where you should update the summary of the preference that's being changed. If you do this, the summary will be updated every time when the value of a preference changes.
  • You should put that code in the onResume() lifecycle method, because you need it called every time the fragment comes into foreground. I recommend that you introduce your sh variable as a class field and in your onResume(), you call this: sh.registerOnSharedPreferenceChangeListener(Main.this). And also don't forget to unregister the callback in the onPause() method, with sh.unregisterOnSharedPreferenceChangeListener(Main.this) (if you don't do this, you may get a null pointer exception when abandoning and returning to the settings fragment and invoking the listener).
  • Yes, and make your SettingsFragment class instantiable, not static, otherwise you wouldn't be able to access the parent object. To make things more convenient, I would however recommend that you keep the parent activity class clean and make the fragment implement the SharedPreferences.OnSharedPreferenceChangeListener instead – in that way, you would be able to reuse your SharedPreferences class field (after having introduced it, provided that you will).
  • This is actually the most easy answer as it does not require changing any code in the fragment or activity or any code related to how the settings are handled or created.
  • But if the user changes the value the summary doesn't get updated, does it?
  • '@JvmOverloads' for the constructor doesn't work in this case, the style of 'EditTextPreferences' will not be applied as you do not call the 'super' constructor this way. Try 'constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)' instead.
  • For ListPreferences you can use 'android:summary="%s"' to show the value as summary.
  • Please don't post links to solutions. Use them to backup your solution only
  • Amazing! no need for any change in code. The actual xml is app:useSimpleSummaryProvider="true" and it was added in preference:1.1.0-alpha01
  • You had to change the getSummary() because @serv-inc answer had the android:summary="Actual value: %s" field set to be used for a String format.