在摘要中显示EditTextPreference的值

时间:2015-12-15 12:10:17

标签: android

我正在学习如何在Android中开发并想要进行设置活动,

我的设置活动

public class Main extends Activity  {


    protected SettingsFragment settingsFragment;


    @SuppressLint("NewApi")
    @TargetApi(11)
    public class SettingsFragment extends PreferenceFragment implements
            SharedPreferences.OnSharedPreferenceChangeListener {


        @Override
        public void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.preferences);
            setSummaries();


        }


        @Override
        public void onResume() {
            final SharedPreferences sh = getPreferenceManager().getSharedPreferences() ;
            super.onResume();
            sh.registerOnSharedPreferenceChangeListener(this);

        }

        @Override
        public void onPause() {
            final SharedPreferences sh = getPreferenceManager().getSharedPreferences() ;
            super.onPause();
            sh.unregisterOnSharedPreferenceChangeListener(this);
        }

        @SuppressLint("NewApi")
        public void setSummaries(){

           final SharedPreferences sh = getPreferenceManager().getSharedPreferences() ;


            //Pref1
            Preference stylePref = findPreference("editTextPref");
            stylePref.setSummary(sh.getString("editTextPref", ""));

            //here the other preferences..
        }


        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
            if (key.equals("editTextPref")) {
                Preference pref = settingsFragment.findPreference(key);
                // Set summary to be the user-description for the selected value
                pref.setSummary(sharedPreferences.getString(key, ""));

            }
            //here the others preferences
        }
    }//End fragment

    @SuppressLint("NewApi")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        settingsFragment = new SettingsFragment();
        getFragmentManager().beginTransaction()
                .replace(android.R.id.content, settingsFragment)
                .commit();


    }


}

和我的res/preferences.xml文件

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <PreferenceCategory
        android:title="BTA"
        xmlns:android="http://schemas.android.com/apk/res/android">


        <EditTextPreference
            android:key="editTextPref"
            android:title="Numero de telephone"
            android:summary="This allows you to enter a string"
            android:defaultValue="*"/>

    </PreferenceCategory>

</PreferenceScreen>

所以现在我有了设置活动的活动。但我想在android:summary中显示EditTextPref的值。 我找到了很多主题,但所有功能都已弃用。

编辑:感谢@Ace_McIntosh,我为想要它的人编辑了我的代码,现在正在运行。

9 个答案:

答案 0 :(得分:7)

只需覆盖getSummary中的EditTextPreference,您将获得一个EditTextPreference,其值将显示为摘要。

public class EditSummaryPreference extends EditTextPreference {
    ...// omit constructor

    @Override
    public CharSequence getSummary() {
        return getText();
    }
}

答案 1 :(得分:4)

只需在所需的Preference对象上使用setSummary method即可。在为您要更新的每个条目(即,您的案例中的所有EditTextPreference条目)恢复设置片段时调用它,并在具体的OnSharedPreferenceChangeListener对象上注册SharedPreferences(以便你可以更新摘要以防它被更改) - 并传递所需的EditTextPreference值(你可以通过它的getText()方法获得)。

在你的MyPreferenceFragment中实现它(我不保证它对蝙蝠起作用,它只是为了给你一个想法):

public class MyPreferenceFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
    SharedPreferences sharedPreferences;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // load the preferences from your XML resource (which I assume you already do anyway)
        addPreferencesFromResource(R.xml.preferences);
    }

    @Override
    public void onResume() {
        super.onResume();

        sharedPreferences = getPreferenceManager().getSharedPreferences();

        // we want to watch the preference values' changes
        sharedPreferences.registerOnSharedPreferenceChangeListener(this);

        Map<String, ?> preferencesMap = sharedPreferences.getAll();
        // iterate through the preference entries and update their summary if they are an instance of EditTextPreference
        for (Map.Entry<String, ?> preferenceEntry : preferencesMap.entrySet()) {
            if (preferenceEntry instanceof EditTextPreference) {
                updateSummary((EditTextPreference) preferenceEntry);
            }
        }
    }

    @Override
    public void onPause() {
        sharedPreferences.unregisterOnSharedPreferenceChangeListener(this);
        super.onPause();
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
                                          String key) {
        Map<String, ?> preferencesMap = sharedPreferences.getAll();

        // get the preference that has been changed
        Object changedPreference = preferencesMap.get(key);
        // and if it's an instance of EditTextPreference class, update its summary
        if (preferencesMap.get(key) instanceof EditTextPreference) {
            updateSummary((EditTextPreference) changedPreference);
        }
    }

    private void updateSummary(EditTextPreference preference) {
        // set the EditTextPreference's summary value to its current text
        preference.setSummary(preference.getText());
    }
}

答案 2 :(得分:3)

(在Kotlin中)我更喜欢做一些更简单的事情,只需创建一个扩展EditTextPreference的类:

import android.content.Context
import android.support.v7.preference.EditTextPreference
import android.util.AttributeSet

/**
 * This class was created by Anthony M Cannon on 17/04/2018.
 */
class SummarisedEditTextPreference @JvmOverloads constructor(context: Context,
    attrs: AttributeSet? = null) : EditTextPreference(context, attrs) {

    private var mOnChangeListener: OnPreferenceChangeListener? = null

    init {
        super.setOnPreferenceChangeListener { preference, newValue ->
            summary = newValue as String
            mOnChangeListener?.onPreferenceChange(preference, newValue) ?: true
        }
    }

    /**
    * Called when this Preference has been attached to a Preference hierarchy.
    * Make sure to call the super implementation.
    *
    * @param preferenceManager The PreferenceManager of the hierarchy.
    */
    override fun onAttachedToHierarchy(preferenceManager: PreferenceManager) {
        super.onAttachedToHierarchy(preferenceManager)
        summary = sharedPreferences.getString(key, null)
    }


    /**
     * Sets the callback to be invoked when this Preference is changed by the
     * user (but before the internal state has been updated).
     *
     * @param onPreferenceChangeListener The callback to be invoked.
     */
    override fun setOnPreferenceChangeListener(
        onPreferenceChangeListener: OnPreferenceChangeListener) {
        mOnChangeListener = onPreferenceChangeListener
    }
}

然后您可以这样使用:

<&lt;您的包名&gt; .SummarisedEditTextPreference/>

答案 3 :(得分:2)

上面发布的示例中有一些错误,所以我想我发布了一个有效的解决方案(也支持ListPreference和MultiSelectListPreference)

public class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {

private SharedPreferences sharedPreferences;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.settings);
}

@Override
public void onResume() {
    super.onResume();

    sharedPreferences = getPreferenceManager().getSharedPreferences();
    sharedPreferences.registerOnSharedPreferenceChangeListener(this);

    PreferenceScreen preferenceScreen = getPreferenceScreen();
    for(int i = 0; i < preferenceScreen.getPreferenceCount(); i++) {
        setSummary(getPreferenceScreen().getPreference(i));
    }
}

@Override
public void onPause() {
    sharedPreferences.unregisterOnSharedPreferenceChangeListener(this);
    super.onPause();
}

@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
    Preference pref = getPreferenceScreen().findPreference(key);
    setSummary(pref);
}

private void setSummary(Preference pref) {
    if (pref instanceof EditTextPreference) {
        updateSummary((EditTextPreference) pref);
    } else if (pref instanceof ListPreference) {
        updateSummary((ListPreference) pref);
    } else if (pref instanceof MultiSelectListPreference) {
        updateSummary((MultiSelectListPreference) pref);
    }
}

private void updateSummary(MultiSelectListPreference pref) {
    pref.setSummary(Arrays.toString(pref.getValues().toArray()));
}

private void updateSummary(ListPreference pref) {
    pref.setSummary(pref.getValue());
}

private void updateSummary(EditTextPreference preference) {
    preference.setSummary(preference.getText());
}
}

答案 4 :(得分:1)

@ serv-inc的回答对我有用。不知何故,只有当价值发生变化时,其他答案才有效。

但在它发挥作用之前,我必须做出如下改动:

@Override
public CharSequence getSummary() {
    return getText();
}

显示最初显示时,值更改时以及恢复后的值。

答案 5 :(得分:1)

布雷顿·切灵顿(Brett Cherringtons)做出回应,在科特林实施。有一个错误,即不支持PreferenceCategories,该错误已通过setSummary中的附加递归循环进行了修复

class SettingsFragment : PreferenceFragment(), SharedPreferences.OnSharedPreferenceChangeListener {

    private lateinit var sharedPreferences: SharedPreferences

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        addPreferencesFromResource(R.xml.preferences)
    }

    override fun onResume() {
        super.onResume()

        sharedPreferences = preferenceManager.sharedPreferences
        sharedPreferences.registerOnSharedPreferenceChangeListener(this)

        val preferenceScreen = preferenceScreen
        for (i in 0 until preferenceScreen.preferenceCount) {
            setSummary(getPreferenceScreen().getPreference(i))
        }
    }

    override fun onPause() {
        sharedPreferences.unregisterOnSharedPreferenceChangeListener(this)
        super.onPause()
    }

    override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) {
        val pref = preferenceScreen.findPreference(key)
        pref?.let { setSummary(it) }
    }

    private fun setSummary(pref: Preference) {
        if (pref is EditTextPreference) {
            updateSummary(pref)
        } else if (pref is ListPreference) {
            updateSummary(pref)
        } else if (pref is MultiSelectListPreference) {
            updateSummary(pref)
        } else if (pref is PreferenceCategory){
            // needs to loop through child preferences
            for (i in 0 until pref.preferenceCount) {
                setSummary(pref.getPreference(i))
            }
        }
    }

    private fun updateSummary(pref: MultiSelectListPreference) {
        pref.setSummary(Arrays.toString(pref.values.toTypedArray()))
    }

    private fun updateSummary(pref: ListPreference) {
        pref.summary = pref.value
    }

    private fun updateSummary(preference: EditTextPreference) {
        preference.summary = preference.text
    }
}

答案 6 :(得分:1)

androidx库中,EditTextPreference具有 app:useSimpleSummaryProvider 属性。使用该属性,您无需扩展任何类或侦听SharedPreferences上的任何更改。您可以在https://github.com/googlesamples/android-preferences/blob/master/app/src/main/res/xml/dialogs.xml

查看示例代码

答案 7 :(得分:1)

如果您使用的是AndroidX Preference library,则可以使用属性 app:useSimpleSummaryProvider 。例如:

<EditTextPreference
        app:key="edittext"
        app:title="@string/title_edittext_preference"
        app:useSimpleSummaryProvider="true"
        app:dialogTitle="@string/dialog_title_edittext_preference"/>

您可以阅读完整的示例here

答案 8 :(得分:0)

除了@Eke Koseoglu的答案。

如果您使用 AndroidX首选项库,则可以通过下面的Kotlin代码设置 summaryProvider

val editTextPreference = EditTextPreference(context)
editTextPreference.summaryProvider = EditTextPreference.SimpleSummaryProvider.getInstance()

根据EditTextPreference.SimpleSummaryProvider的文档;

  

如果未设置任何值,则显示的摘要将为“未设置”,   否则,显示的摘要将是为此设置的值   偏好。