Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying EditTextPreference current value in summary

I want to be able to display the value of an EditTextPreference in the summary field. Specifically, I want to do this within PreferenceFragmentCompat.

import android.support.v7.preference.PreferenceFragmentCompat;

public class SettingsFragment extends PreferenceFragmentCompat {

    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        addPreferencesFromResource(R.xml.preferences);
    }
}

Preference file looks like this:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <EditTextPreference
        android:defaultValue="DEVICE01"
        android:key="device_id"
        android:title="Device ID" />
</PreferenceScreen>

I have seen other solutions, but none of them included how to do this within PreferenceFragmentCompat.

like image 749
japkin Avatar asked Feb 19 '26 10:02

japkin


2 Answers

As this question still pops up on Google, there is now a more direct way to solve this (using androidx).

<PreferenceScreen 
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <EditTextPreference
        android:key="prefFoobar"
        android:title="@string/preference_foobar"
        android:persistent="true"
        app:useSimpleSummaryProvider="true" />
</PreferenceScreen>

The "app:useSimpleSummaryProvider" does all the magic.

like image 63
Simon Avatar answered Feb 21 '26 00:02

Simon


I think, it's the same way as in every simple PreferenceFragment: In xml file:

android:summary="@string/your_string_resource"

In code:

    EditTextPreference editTextPreference = (EditTextPreference) findPreference(YOUR_PREFERENCE_KEY);
    editTextPreference.setSummary(sharedPreferences.getString(YOUR_PREFERENCE_KEY, defaultValue));
    editTextPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object o) {

            String yourString = o.toString();
            sharedPreferences.edit().putString(YOUR_PREFERENCE_KEY, yourString).apply();
            editTextPreference.setSummary(yourString);

            return true;
        }
    });
like image 40
grabarz121 Avatar answered Feb 21 '26 00:02

grabarz121



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!