Summary to describe the current value

When I try to set a pivot, when users select a preference item, it usually persists. But when my application is restarted, the resume failed.

Here is my code to set the summary for ListPreference

and EditTextPreference

:

public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key){

    Preference pref = findPreference(key);

    // I feel the problem is happened here
    if (pref instanceof ListPreference) {
        ListPreference listPref = (ListPreference) pref;
        pref.setSummary(listPref.getEntry());
    }
    // Same problem here
    if (pref instanceof EditTextPreference) {
        EditTextPreference editText = (EditTextPreference) pref;
        pref.setSummary(editText.getEntry().toString());
    }
}

      

Something is wrong?

+3


source to share


3 answers


if you want to show the current record try setting the summary in xml:

android:summary="%s"

      



This only works for ListPreference

(see doc ):

If the summary has a String formatting marker (ie "% s" or "% 1 $ s") then the current value of the entry will be replaced instead.

+26


source


The problem might be that the listener is not called on startup (the value does not change). But you can set a dynamic view in XML. For ListPreference

, this is inline and @FreshD's answer is the way to go. To go to f.ex. a EditTextPreference

, you need to create your own class. for example



package your.package;

import android.content.Context;
import android.util.AttributeSet;

public class EditTextPreference extends android.preference.EditTextPreference{
        public EditTextPreference(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
        }

        public EditTextPreference(Context context, AttributeSet attrs) {
            super(context, attrs);
        }

        public EditTextPreference(Context context) {
            super(context);
        }

        @Override
        public CharSequence getSummary() {
            String summary = super.getSummary().toString();
            return String.format(summary, getText());
        }
    }

      

And use this in your xml:

<your.package.EditTextPreference
                android:key="pref_alpha"
                android:summary="Actual value: %s"
                android:title="Title"
                android:defaultValue="default"
                />

      

+5


source


 ListPreference listPref = (ListPreference) findPreference("listkey");
 listPref.setSummary(listPref.getEntry());

 EditTextPreference editText = (EditTextPreference) findPreference("edittextkey");
 editText.setSummary(editText.getEntry().toString());

      

If you have the key then set the pivot as above in oncreate after addpreferences in your Fragment or Activity preference

+2


source







All Articles