Setting UI preference Summary field to the value of the preference
Asked Answered
L

4

26

New to Android, I have some code when the user changes a preference I update the Summary field in the UI preference to be the value they entered. However, when the preference activity is created I'd like to set the Summary fields to be the values in the corresponding preferences. Please advise. Thanks.

public class MyPreferenceActivity extends PreferenceActivity implements
        OnSharedPreferenceChangeListener {

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preference);
        SharedPreferences sp = getPreferenceScreen().getSharedPreferences();
        sp.registerOnSharedPreferenceChangeListener(this);
    }

    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
            String key) {
        Preference pref = findPreference(key);
        if (pref instanceof EditTextPreference) {
            EditTextPreference etp = (EditTextPreference) pref;
            pref.setSummary(etp.getText());
        }
    }
}
Little answered 30/9, 2010 at 2:51 Comment(1)
N
50

I am new too so may not be the best code but this is similar to what I am doing. You probably want to register you listener onResume and unregister it onPause though rather than onCreate. I hope this helps.

Mainly you just need to grab the pref, the pref value and set the summary.

public class MyPreferenceActivity extends PreferenceActivity implements
        OnSharedPreferenceChangeListener {

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preference);
        SharedPreferences sp = getPreferenceScreen().getSharedPreferences();
        EditTextPreference editTextPref = (EditTextPreference) findPreference("thePrefKey");
        editTextPref
                .setSummary(sp.getString("thePrefKey", "Some Default Text"));
    }

    protected void onResume() {
        super.onResume();
        getPreferenceScreen().getSharedPreferences()
                .registerOnSharedPreferenceChangeListener(this);
    }

    protected void onPause() {
        super.onPause();
        getPreferenceScreen().getSharedPreferences()
                .unregisterOnSharedPreferenceChangeListener(this);
    }

    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
            String key) {
        Preference pref = findPreference(key);
        if (pref instanceof EditTextPreference) {
            EditTextPreference etp = (EditTextPreference) pref;
            pref.setSummary(etp.getText());
        }
    }
}
Nettles answered 23/10, 2010 at 12:12 Comment(4)
It is working for me. It only fired when the value is changed. So you need to preset the summary onCreated if your setting already contains value. SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); String email = sharedPreferences.getString("prefUsername", "NULL"); EditTextPreference prefUsername = (EditTextPreference)findPreference("prefUsername"); prefUsername.setSummary(email);Abramabramo
Question: why did this answer (and the original question) cast to EditTextPreference? setSummary is a method of Preference. Is there a specific reason to cast? I'm just trying to understand.Heng
@GaryS. The getText() method is not available in Preference.Acriflavine
Thanks, @NiekHaarman. I didn't notice the cast in onSharedPreferenceChanged. I was referring to the cast in onCreate. I'm guessing the cast there isn't necessary.Heng
P
7

This worked for me.

public class PrefsActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener
{
    private Preference pref;
    private String summaryStr;
    String prefixStr;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
       super.onCreate(savedInstanceState);
       addPreferencesFromResource(R.xml.prefs);

       SharedPreferences sharedPref = getPreferenceScreen().getSharedPreferences();
       sharedPref.registerOnSharedPreferenceChangeListener(this);      
    }

    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
    {
        //Get the current summary
        pref = findPreference(key);
        summaryStr = (String)pref.getSummary();

        //Get the user input data
        prefixStr = sharedPreferences.getString(key, "");

        //Update the summary with user input data
        pref.setSummary(summaryStr.concat(": [").concat(prefixStr).concat("]"));
    }
}   
Phoenix answered 11/7, 2012 at 2:2 Comment(0)
S
1

What I usually do is:
1 - Make a new class which extends the kind of preference I need to show (1 per preference type) 2 - Inside its code, do the appropriate actiob to show the updated summary
3 - Refer this class in the res/xml/preferences.xml file

Let me swo a small example, good for an EditTextPreference:

CLS_Prefs_Edit.java

/**
 * CLS_Prefs_Edit class
 *
 * This is the class that allows for a custom EditTextPrefence
 * (auto refresh summary).
 *
 * @category    Custom Preference
 * @author        Luca Crisi ([email protected])
 * @copyright    Luca Crisi
 * @version        1.0
 */
package com.your_name.your_app;

/* -------------------------------- Imports --------------------------------- */

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

public final class CLS_Prefs_Edit
extends EditTextPreference
{

    /* ---------------------------- Constructors ---------------------------- */

    public CLS_Prefs_Edit(final Context ctx, final AttributeSet attrs)
    {
        super(ctx, attrs);
    }
    public CLS_Prefs_Edit(final Context ctx)
    {
        super(ctx);
    }

    /* ----------------------------- Overrides ------------------------------ */

    @Override
    public void setText(final String value)
    {
        super.setText(value);
        setSummary(getText());
    }
}

res/xml/preferences.xml

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
    xmlns:android="http://schemas.android.com/apk/res/android"
    >
    <PreferenceCategory android:title="@string/pref_phone_cat">
<!-- NORMAL EditTextPreference, NO summary update -->
<!--         <EditTextPreference -->
<!--             android:widgetLayout="@layout/arr_dn" -->
<!--             android:key="phone" -->
<!--             android:title="@string/pref_phone_title" -->
<!--             android:summary="@string/pref_phone_summ" -->
<!--             android:defaultValue="" -->
<!--             android:inputType="phone" -->
<!--             android:digits="+1234567890" -->
<!--         /> -->
<!-- MY EditTextPreference, WITH summary update -->
        <com.your_name.your_app.CLS_Prefs_Edit
            android:widgetLayout="@layout/arr_dn"
            android:key="phone"
            android:title="@string/pref_phone_title"
            android:summary="@string/pref_phone_summ"
            android:defaultValue=""
            android:inputType="phone"
            android:digits="+1234567890"
        />
    </PreferenceCategory>
</PreferenceScreen>

Of course, set your strings in /res/values/strings, and you're done.

Note that this solution works for both PreferenceFragments and PreferenceActivities.
I'm using it for an app tha runs on 2.2 Froyo (showing a PreferenceActivity) as well as on 4.4 KitKat (showing a PreferenceFragment)

I hope it helps.

Stratton answered 29/11, 2013 at 14:22 Comment(1)
While this works, that will introduce bad dependency between setText() and setSummary() calls. For example, android framework can decide to call setSummary() with empty string (to apply value from xml) after setText() was called.Athanasia
C
0

First, for your class:

class SettingsFragment : SettingsBaseFragment(),
    // Make sure you implement the OnSharedPreferenceChangeListener
    SharedPreferences.OnSharedPreferenceChangeListener,
    Preference.OnPreferenceClickListener {}

Next, in the onSharedPreferenceChanged, you have a reference to the sharedPreference, which you can use to get the preference result. Then you can use the latest result you get to alter the summary:

override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) {
        when (key) {
            SETTINGS_AUTO_SETTLEMENT -> refreshSummaryForAutoSettlement(sharedPreferences?.getBoolean(SETTINGS_AUTO_SETTLEMENT, false))
        }
    }

// helper function for altering the summary for the preference
private fun refreshSummaryForAutoSettlement(isAutoSettlementEnabled: Boolean?) {
    when (isAutoSettlementEnabled != null && isAutoSettlementEnabled) {
        true -> findPreference(SETTINGS_AUTO_SETTLEMENT).summary = getString(R.string.auto_settlement_enabled_summary)
        false -> findPreference(SETTINGS_AUTO_SETTLEMENT).summary = getString(R.string.auto_settlement_disabled_summary)
    }
}
Coccidioidomycosis answered 9/8, 2019 at 18:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.