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.
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;
}
});