将UI首选项“摘要”字段设置为首选项的值

时间:2010-09-30 02:51:16

标签: android android-preferences

Android新手,我在用户更改首选项时有一些代码我将UI首选项中的“摘要”字段更新为他们输入的值。但是,在创建首选项活动时,我想将“摘要”字段设置为相应首选项中的值。 请指教。谢谢。

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

4 个答案:

答案 0 :(得分:47)

我也是新手,所以可能不是最好的代码,但这与我正在做的相似。您可能希望在onResume上注册监听器并将其取消注册onPause,而不是onCreate。我希望这会有所帮助。

主要是你只需要获取pref,pref值并设置摘要。

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

答案 1 :(得分:7)

这对我有用。

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("]"));
    }
}   

答案 2 :(得分:1)

我通常做的是:
1 - 创建一个新类,扩展我需要显示的首选项(每个首选项类型1个) 2 - 在其代码内部,执行适当的活动以显示更新的摘要
3 - 在 res / xml / preferences.xml 文件中引用此类

让我举一个小例子,适合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 (luca.crisi.lc@gmail.com)
 * @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>

当然,在/ res / values / strings中设置你的字符串,你就完成了。

请注意,此解决方案适用于PreferenceFragments和PreferenceActivities 我正在使用它来运行2.2 Froyo(显示PreferenceActivity)以及4.4 KitKat(显示PreferenceFragment)的应用程序

我希望它有所帮助。

答案 3 :(得分:0)

首先,对于您的课程:

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

接下来,在onSharedPreferenceChanged中,有对sharedPreference的引用,您可以使用该引用来获取首选项结果。然后,您可以使用获得的最新结果来更改摘要:

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