如何在首选项摘要中显示android首选项的当前值?

wpcxdonn  于 2021-08-20  发布在  Java
关注(0)|答案(30)|浏览(685)

这一定经常发生。
当用户在android应用程序中编辑首选项时,我希望他们能够在应用程序中看到当前设置的首选项值 Preference 总结。
示例:如果我有“丢弃旧邮件”的首选项设置,该设置指定需要清理邮件的天数。在 PreferenceActivity 我希望用户看到:
“丢弃旧邮件”<-标题
“x天后清理邮件”<-摘要,其中x是当前首选项值
额外积分:使其可重用,这样我就可以轻松地将其应用于我所有的首选项,而不管它们的类型如何(这样它就可以用最少的编码处理edittextpreference、listpreference等)。

vsikbqxv

vsikbqxv1#

在android studio中,打开“root_preferences.xml”,选择设计模式。选择所需的edittextpreference首选项,并在“所有属性”下查找“usesimplesummaryprovider”属性并将其设置为true。然后它将显示当前值。

izkcnapc

izkcnapc2#

设置 ListPreference 对于在对话框中选择的值,可以使用以下代码:

  1. package yourpackage;
  2. import android.content.Context;
  3. import android.util.AttributeSet;
  4. public class ListPreference extends android.preference.ListPreference {
  5. public ListPreference(Context context, AttributeSet attrs) {
  6. super(context, attrs);
  7. }
  8. protected void onDialogClosed(boolean positiveResult) {
  9. super.onDialogClosed(positiveResult);
  10. if (positiveResult) setSummary(getEntry());
  11. }
  12. protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
  13. super.onSetInitialValue(restoreValue, defaultValue);
  14. setSummary(getEntry());
  15. }
  16. }

并参考 yourpackage.ListPreference 在你的 preferences.xml 记得在那里指定你的名字 android:defaultValue 因为这会触发对 onSetInitialValue() .
如果需要,您可以在调用之前修改文本 setSummary() 任何适合你的申请。

展开查看全部
o0lyfsai

o0lyfsai3#

如果您使用的是androidx,则可以使用自定义 SummaryProvider . 这种方法可用于任何情况 Preference .
文档(java)中的示例:

  1. EditTextPreference countingPreference = (EditTextPreference) findPreference("counting");
  2. countingPreference.setSummaryProvider(new SummaryProvider<EditTextPreference>() {
  3. @Override
  4. public CharSequence provideSummary(EditTextPreference preference) {
  5. String text = preference.getText();
  6. if (TextUtils.isEmpty(text)){
  7. return "Not set";
  8. }
  9. return "Length of saved value: " + text.length();
  10. }
  11. });

文档中的示例(kotlin):

  1. val countingPreference = findPreference("counting") as EditTextPreference
  2. countingPreference.summaryProvider = SummaryProvider<EditTextPreference> { preference ->
  3. val text = preference.text
  4. if (TextUtils.isEmpty(text)) {
  5. "Not set"
  6. } else {
  7. "Length of saved value: " + text.length
  8. }
  9. }
展开查看全部
crcmnpdw

crcmnpdw4#

我的解决方案是创建一个自定义 EditTextPreference ,在xml中使用,如下所示: <com.example.EditTextPreference android:title="Example Title" /> edittextpreference.java:-

  1. package com.example;
  2. import android.content.Context;
  3. import android.util.AttributeSet;
  4. public class EditTextPreference extends android.preference.EditTextPreference
  5. {
  6. public EditTextPreference(Context context, AttributeSet attrs, int defStyle)
  7. {
  8. super(context, attrs, defStyle);
  9. }
  10. public EditTextPreference(Context context, AttributeSet attrs)
  11. {
  12. super(context, attrs);
  13. }
  14. public EditTextPreference(Context context)
  15. {
  16. super(context, null);
  17. }
  18. @Override
  19. protected void onDialogClosed(boolean positiveResult)
  20. {
  21. super.onDialogClosed(positiveResult);
  22. setSummary(getSummary());
  23. }
  24. @Override
  25. public CharSequence getSummary()
  26. {
  27. return getText();
  28. }
  29. }
展开查看全部
oxalkeyp

oxalkeyp5#

对于edittextpreference:
当然,如果您需要特定的edittextpreference,我会想到这个解决方案,但您可以对每个preference都这样做:
............

  1. private static final String KEY_EDIT_TEXT_PREFERENCE2 = "on_a1";
  2. public static String value = "";

............

  1. private void updatePreference(Preference preference, String key) {
  2. if (key.equals(KEY_EDIT_TEXT_PREFERENCE2)) {
  3. preference = findPreference(key);
  4. if (preference instanceof EditTextPreference) {
  5. editTextPreference = (EditTextPreference) preference;
  6. editTextPreference.setSummary(editTextPreference.getText());
  7. value = editTextPreference.getText().toString();
  8. return;
  9. }
  10. SharedPreferences sharedPrefs = getPreferenceManager().getSharedPreferences();
  11. preference.setSummary(sharedPrefs.getString(KEY_EDIT_TEXT_PREFERENCE2, ""));
  12. }
  13. }

然后在onresume()中;

  1. @Override
  2. public void onResume() {
  3. super.onResume();
  4. SharedPreferences etext = getPreferenceManager().getSharedPreferences();
  5. String str = etext.getString("value", "");
  6. editTextPreference = (EditTextPreference) findPreference(KEY_EDIT_TEXT_PREFERENCE2);
  7. editTextPreference.setText(str);
  8. editTextPreference.setSummary(editTextPreference.getText());
  9. getPreferenceScreen().getSharedPreferences()
  10. .registerOnSharedPreferenceChangeListener(this);
  11. }

在:

  1. @Override
  2. public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
  3. updatePreference(findPreference(key), key);
  4. }
展开查看全部
yi0zb3m4

yi0zb3m46#

必须在oncreate方法上使用bindpreferencesummarytovalue函数。
例子:

  1. @Override
  2. public void onCreate(Bundle savedInstanceState) {
  3. super.onCreate(savedInstanceState);
  4. // Add 'general' preferences, defined in the XML file
  5. addPreferencesFromResource(R.xml.pref_general);
  6. // For all preferences, attach an OnPreferenceChangeListener so the UI summary can be
  7. // updated when the preference changes.
  8. bindPreferenceSummaryToValue(findPreference(getString(R.string.pref_location_key)));
  9. bindPreferenceSummaryToValue(findPreference(getString(R.string.pref_units_key)));
  10. }

参见第3课关于udacity android课程:https://www.udacity.com/course/viewer#!/c-ud853/l-1474559101/e-1643578599/m-1643578601

piok6c0g

piok6c0g7#

这里,所有这些都是从eclipse示例中截取的 SettingsActivity . 我必须复制所有这些太多的代码来展示这些android开发者如何完美地选择更通用和稳定的编码风格。
我留下了修改密码 PreferenceActivity 到平板电脑和更大的api。

  1. public class SettingsActivity extends PreferenceActivity {
  2. @Override
  3. protected void onPostCreate(Bundle savedInstanceState) {
  4. super.onPostCreate(savedInstanceState);
  5. setupSummaryUpdatablePreferencesScreen();
  6. }
  7. private void setupSummaryUpdatablePreferencesScreen() {
  8. // In the simplified UI, fragments are not used at all and we instead
  9. // use the older PreferenceActivity APIs.
  10. // Add 'general' preferences.
  11. addPreferencesFromResource(R.xml.pref_general);
  12. // Bind the summaries of EditText/List/Dialog preferences to
  13. // their values. When their values change, their summaries are updated
  14. // to reflect the new value, per the Android Design guidelines.
  15. bindPreferenceSummaryToValue(findPreference("example_text"));
  16. bindPreferenceSummaryToValue(findPreference("example_list"));
  17. }
  18. /**
  19. * A preference value change listener that updates the preference's summary
  20. * to reflect its new value.
  21. */
  22. private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
  23. private String TAG = SettingsActivity.class.getSimpleName();
  24. @Override
  25. public boolean onPreferenceChange(Preference preference, Object value) {
  26. String stringValue = value.toString();
  27. if (preference instanceof ListPreference) {
  28. // For list preferences, look up the correct display value in
  29. // the preference's 'entries' list.
  30. ListPreference listPreference = (ListPreference) preference;
  31. int index = listPreference.findIndexOfValue(stringValue);
  32. // Set the summary to reflect the new value.
  33. preference.setSummary(
  34. index >= 0
  35. ? listPreference.getEntries()[index]
  36. : null);
  37. } else {
  38. // For all other preferences, set the summary to the value's
  39. // simple string representation.
  40. preference.setSummary(stringValue);
  41. }
  42. Log.i(TAG, "pref changed : " + preference.getKey() + " " + value);
  43. return true;
  44. }
  45. };
  46. /**
  47. * Binds a preference's summary to its value. More specifically, when the
  48. * preference's value is changed, its summary (line of text below the
  49. * preference title) is updated to reflect the value. The summary is also
  50. * immediately updated upon calling this method. The exact display format is
  51. * dependent on the type of preference.
  52. *
  53. * @see #sBindPreferenceSummaryToValueListener
  54. */
  55. private static void bindPreferenceSummaryToValue(Preference preference) {
  56. // Set the listener to watch for value changes.
  57. preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
  58. // Trigger the listener immediately with the preference's
  59. // current value.
  60. sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
  61. PreferenceManager
  62. .getDefaultSharedPreferences(preference.getContext())
  63. .getString(preference.getKey(), ""));
  64. }
  65. }
  66. ``` `xml/pref_general.xml` ```
  67. <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
  68. <!-- NOTE: EditTextPreference accepts EditText attributes. -->
  69. <!-- NOTE: EditTextPreference's summary should be set to its value by the activity code. -->
  70. <EditTextPreference
  71. android:capitalize="words"
  72. android:defaultValue="@string/pref_default_display_name"
  73. android:inputType="textCapWords"
  74. android:key="example_text"
  75. android:maxLines="1"
  76. android:selectAllOnFocus="true"
  77. android:singleLine="true"
  78. android:title="@string/pref_title_display_name" />
  79. <!-- NOTE: Hide buttons to simplify the UI. Users can touch outside the dialog todismiss it.-->
  80. <!-- NOTE: ListPreference's summary should be set to its value by the activity code. -->
  81. <ListPreference
  82. android:defaultValue="-1"
  83. android:entries="@array/pref_example_list_titles"
  84. android:entryValues="@array/pref_example_list_values"
  85. android:key="example_list"
  86. android:negativeButtonText="@null"
  87. android:positiveButtonText="@null"
  88. android:title="@string/pref_title_add_friends_to_messages" />
  89. </PreferenceScreen>
  90. ``` `values/strings_activity_settings.xml` ```
  91. <resources>
  92. <!-- Strings related to Settings -->
  93. <!-- Example General settings -->
  94. <string name="pref_title_display_name">Display name</string>
  95. <string name="pref_default_display_name">John Smith</string>
  96. <string name="pref_title_add_friends_to_messages">Add friends to messages</string>
  97. <string-array name="pref_example_list_titles">
  98. <item>Always</item>
  99. <item>When possible</item>
  100. <item>Never</item>
  101. </string-array>
  102. <string-array name="pref_example_list_values">
  103. <item>1</item>
  104. <item>0</item>
  105. <item>-1</item>
  106. </string-array>
  107. </resources>

注:事实上,我只是想评论一下“谷歌的preferenceactivity示例也很有趣”。但是我没有足够的声望点,所以请不要怪我。
(抱歉英语不好)

展开查看全部
w1jd8yoj

w1jd8yoj8#

由于在androidx中,首选项类具有summaryprovider接口,因此可以在不使用onsharedpreferencechangelistener的情况下完成。edittextpreference和listpreference提供了简单的实现。根据eddieb的答案,它可能是这样的。在androidx上测试。首选项:首选项:1.1.0-alpha03。

  1. package com.example.util.timereminder.ui.prefs;
  2. import android.os.Bundle;
  3. import com.example.util.timereminder.R;
  4. import androidx.preference.EditTextPreference;
  5. import androidx.preference.ListPreference;
  6. import androidx.preference.Preference;
  7. import androidx.preference.PreferenceFragmentCompat;
  8. import androidx.preference.PreferenceGroup;
  9. /**
  10. * Displays different preferences.
  11. */
  12. public class PrefsFragmentExample extends PreferenceFragmentCompat {
  13. @Override
  14. public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
  15. addPreferencesFromResource(R.xml.preferences);
  16. initSummary(getPreferenceScreen());
  17. }
  18. /**
  19. * Walks through all preferences.
  20. *
  21. * @param p The starting preference to search from.
  22. */
  23. private void initSummary(Preference p) {
  24. if (p instanceof PreferenceGroup) {
  25. PreferenceGroup pGrp = (PreferenceGroup) p;
  26. for (int i = 0; i < pGrp.getPreferenceCount(); i++) {
  27. initSummary(pGrp.getPreference(i));
  28. }
  29. } else {
  30. setPreferenceSummary(p);
  31. }
  32. }
  33. /**
  34. * Sets up summary providers for the preferences.
  35. *
  36. * @param p The preference to set up summary provider.
  37. */
  38. private void setPreferenceSummary(Preference p) {
  39. // No need to set up preference summaries for checkbox preferences because
  40. // they can be set up in xml using summaryOff and summary On
  41. if (p instanceof ListPreference) {
  42. p.setSummaryProvider(ListPreference.SimpleSummaryProvider.getInstance());
  43. } else if (p instanceof EditTextPreference) {
  44. p.setSummaryProvider(EditTextPreference.SimpleSummaryProvider.getInstance());
  45. }
  46. }
  47. }
展开查看全部
but5z9lq

but5z9lq9#

供参考:

  1. findPreference(CharSequence key)
  2. This method was deprecated in API level 11. This function is not relevant
  3. for a modern fragment-based PreferenceActivity.

这就更有理由去看这张非常光滑的照片 Answer 上面的@asd(此处找到来源)说要使用 %s 在里面 android:summary 对于中的每个字段 preferences.xml . (优先权的当前值被替换为 %s .)

  1. <ListPreference
  2. ...
  3. android:summary="Length of longest word to return as match is %s"
  4. ...
  5. />
6kkfgxo0

6kkfgxo010#

简单地说:

  1. listPreference.setSummary("%s");
vngu2lb8

vngu2lb811#

以下是我的解决方案:

构建首选项类型“getter”方法。

  1. protected String getPreference(Preference x) {
  2. // http://stackoverflow.com/questions/3993982/how-to-check-type-of-variable-in-java
  3. if (x instanceof CheckBoxPreference)
  4. return "CheckBoxPreference";
  5. else if (x instanceof EditTextPreference)
  6. return "EditTextPreference";
  7. else if (x instanceof ListPreference)
  8. return "ListPreference";
  9. else if (x instanceof MultiSelectListPreference)
  10. return "MultiSelectListPreference";
  11. else if (x instanceof RingtonePreference)
  12. return "RingtonePreference";
  13. else if (x instanceof SwitchPreference)
  14. return "SwitchPreference";
  15. else if (x instanceof TwoStatePreference)
  16. return "TwoStatePreference";
  17. else if (x instanceof DialogPreference) // Needs to be after ListPreference
  18. return "DialogPreference";
  19. else
  20. return "undefined";
  21. }

构建“setsummaryinit”方法。

  1. public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
  2. Log.i(TAG, "+ onSharedPreferenceChanged(prefs:" + prefs + ", key:" + key + ")");
  3. if( key != null ) {
  4. updatePreference(prefs, key);
  5. setSummary(key);
  6. } else {
  7. Log.e(TAG, "Preference without key!");
  8. }
  9. Log.i(TAG, "- onSharedPreferenceChanged()");
  10. }
  11. protected boolean setSummary() {
  12. return _setSummary(null);
  13. }
  14. protected boolean setSummary(String sKey) {
  15. return _setSummary(sKey);
  16. }
  17. private boolean _setSummary(String sKey) {
  18. if (sKey == null) Log.i(TAG, "Initializing");
  19. else Log.i(TAG, sKey);
  20. // Get Preferences
  21. SharedPreferences sharedPrefs = PreferenceManager
  22. .getDefaultSharedPreferences(this);
  23. // Iterate through all Shared Preferences
  24. // http://stackoverflow.com/questions/9310479/how-to-iterate-through-all-keys-of-shared-preferences
  25. Map<String, ?> keys = sharedPrefs.getAll();
  26. for (Map.Entry<String, ?> entry : keys.entrySet()) {
  27. String key = entry.getKey();
  28. // Do work only if initializing (null) or updating specific preference key
  29. if ( (sKey == null) || (sKey.equals(key)) ) {
  30. String value = entry.getValue().toString();
  31. Preference pref = findPreference(key);
  32. String preference = getPreference(pref);
  33. Log.d("map values", key + " | " + value + " | " + preference);
  34. pref.setSummary(key + " | " + value + " | " + preference);
  35. if (sKey != null) return true;
  36. }
  37. }
  38. return false;
  39. }
  40. private void updatePreference(SharedPreferences prefs, String key) {
  41. Log.i(TAG, "+ updatePreference(prefs:" + prefs + ", key:" + key + ")");
  42. Preference pref = findPreference(key);
  43. String preferenceType = getPreference(pref);
  44. Log.i(TAG, "preferenceType = " + preferenceType);
  45. Log.i(TAG, "- updatePreference()");
  46. }

初始化

创建包含preferenceactivity并实现onsharedpreferencechangelistener的公共类

  1. protected void onCreate(Bundle savedInstanceState) {
  2. super.onCreate(savedInstanceState);
  3. PreferenceManager.setDefaultValues(this, R.xml.global_preferences,
  4. false);
  5. this.addPreferencesFromResource(R.xml.global_preferences);
  6. this.getPreferenceScreen().getSharedPreferences()
  7. .registerOnSharedPreferenceChangeListener(this);
  8. }
  9. protected void onResume() {
  10. super.onResume();
  11. setSummary();
  12. }
展开查看全部
apeeds0o

apeeds0o12#

如果您只想将每个字段的纯文本值显示为其摘要,那么下面的代码应该是最容易维护的代码。它只需要两次更改(第13行和第21行,标有“此处更改”):

  1. package com.my.package;
  2. import android.content.SharedPreferences;
  3. import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
  4. import android.os.Bundle;
  5. import android.preference.EditTextPreference;
  6. import android.preference.ListPreference;
  7. import android.preference.Preference;
  8. import android.preference.PreferenceActivity;
  9. public class PreferencesActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener {
  10. private final String[] mAutoSummaryFields = { "pref_key1", "pref_key2", "pref_key3" }; // change here
  11. private final int mEntryCount = mAutoSummaryFields.length;
  12. private Preference[] mPreferenceEntries;
  13. @SuppressWarnings("deprecation")
  14. @Override
  15. public void onCreate(Bundle savedInstanceState) {
  16. super.onCreate(savedInstanceState);
  17. addPreferencesFromResource(R.xml.preferences_file); // change here
  18. mPreferenceEntries = new Preference[mEntryCount];
  19. for (int i = 0; i < mEntryCount; i++) {
  20. mPreferenceEntries[i] = getPreferenceScreen().findPreference(mAutoSummaryFields[i]);
  21. }
  22. }
  23. @SuppressWarnings("deprecation")
  24. @Override
  25. protected void onResume() {
  26. super.onResume();
  27. for (int i = 0; i < mEntryCount; i++) {
  28. updateSummary(mAutoSummaryFields[i]); // initialization
  29. }
  30. getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); // register change listener
  31. }
  32. @SuppressWarnings("deprecation")
  33. @Override
  34. protected void onPause() {
  35. super.onPause();
  36. getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this); // unregister change listener
  37. }
  38. private void updateSummary(String key) {
  39. for (int i = 0; i < mEntryCount; i++) {
  40. if (key.equals(mAutoSummaryFields[i])) {
  41. if (mPreferenceEntries[i] instanceof EditTextPreference) {
  42. final EditTextPreference currentPreference = (EditTextPreference) mPreferenceEntries[i];
  43. mPreferenceEntries[i].setSummary(currentPreference.getText());
  44. }
  45. else if (mPreferenceEntries[i] instanceof ListPreference) {
  46. final ListPreference currentPreference = (ListPreference) mPreferenceEntries[i];
  47. mPreferenceEntries[i].setSummary(currentPreference.getEntry());
  48. }
  49. break;
  50. }
  51. }
  52. }
  53. public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
  54. updateSummary(key);
  55. }
  56. }
展开查看全部
rjee0c15

rjee0c1513#

  1. public class ProfileManagement extends PreferenceActivity implements
  2. OnPreferenceChangeListener {
  3. EditTextPreference screenName;
  4. ListPreference sex;
  5. @Override
  6. protected void onCreate(Bundle savedInstanceState) {
  7. super.onCreate(savedInstanceState);
  8. addPreferencesFromResource(R.layout.profile_management);
  9. screenName = (EditTextPreference) findPreference("editTextPref");
  10. sex = (ListPreference) findPreference("sexSelector");
  11. screenName.setOnPreferenceChangeListener(this);
  12. sex.setOnPreferenceChangeListener(this);
  13. }
  14. @Override
  15. public boolean onPreferenceChange(Preference preference, Object newValue) {
  16. preference.setSummary(newValue.toString());
  17. return true;
  18. }
  19. }
展开查看全部
t1qtbnec

t1qtbnec14#

我用listpreference的以下后代解决了这个问题:

  1. public class EnumPreference extends ListPreference {
  2. public EnumPreference(Context aContext, AttributeSet attrs) {
  3. super(aContext,attrs);
  4. }
  5. @Override
  6. protected View onCreateView(ViewGroup parent) {
  7. setSummary(getEntry());
  8. return super.onCreateView(parent);
  9. }
  10. @Override
  11. protected boolean persistString(String aNewValue) {
  12. if (super.persistString(aNewValue)) {
  13. setSummary(getEntry());
  14. notifyChanged();
  15. return true;
  16. } else {
  17. return false;
  18. }
  19. }
  20. }

从1.6到4.0.4,对我来说似乎工作得很好。

展开查看全部
cpjpxq1n

cpjpxq1n15#

我已经看到所有投票的答案都显示了如何将摘要设置为准确的当前值,但op也希望类似于:
“x天后清理邮件”*<-摘要,其中x是当前首选项值
以下是我实现这一目标的答案
根据 ListPreference.getSummary() :
返回此listpreference的摘要。如果摘要中有字符串格式标记(即“%s”或“%1$s”),则将替换当前条目值。
然而,我在几个设备上试过这个,但似乎不起作用。通过一些研究,我在这个答案中找到了一个很好的解决方案。它只包括扩展每个 Preference 您可以使用并覆盖 getSummary() 按照android文档的规定工作。

相关问题