如何监听 PreferenceFragment 中的偏好变化?
Posted
技术标签:
【中文标题】如何监听 PreferenceFragment 中的偏好变化?【英文标题】:How to listen for preference changes within a PreferenceFragment? 【发布时间】:2012-11-15 18:48:03 【问题描述】:如here 所述,我将 PreferenceFragment 子类化并在 Activity 中显示它。该文档解释了如何监听首选项更改here,但前提是您将 PreferenceActivity 子类化。既然我不这样做,我如何监听偏好变化?
我尝试在我的 PreferenceFragment 中实现 OnSharedPreferenceChangeListener,但它似乎不起作用(onSharedPreferenceChanged
似乎从未被调用过)。
这是我目前的代码:
SettingsActivity.java
public class SettingsActivity extends Activity
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
// Display the fragment as the main content.
getFragmentManager().beginTransaction().replace(android.R.id.content, new SettingsFragment()).commit();
SettingsFragment.java
public class SettingsFragment extends PreferenceFragment implements OnSharedPreferenceChangeListener
public static final String KEY_PREF_EXERCISES = "pref_number_of_exercises";
@Override
public void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
//IT NEVER GETS IN HERE!
if (key.equals(KEY_PREF_EXERCISES))
// Set summary to be the user-description for the selected value
Preference exercisesPref = findPreference(key);
exercisesPref.setSummary(sharedPreferences.getString(key, ""));
preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<EditTextPreference
android:defaultValue="15"
android:enabled="true"
android:key="pref_number_of_exercises"
android:numeric="integer"
android:title="Number of exercises" />
</PreferenceScreen>
另外,PreferenceFragment 是否是监听偏好变化的正确位置,还是应该在 Activity 中进行?
【问题讨论】:
对于您的最后一个问题,这完全取决于您的设计框架。在 Android 上很难使用 MVC 或 MVP 方法,但我尝试让我的所有操作都发生在托管片段的活动(控制器)中,并且片段只是 ui(视图/演示者) 【参考方案1】:使用 PreferenceFragmentCompat 解决 Kotlin 问题
https://developer.android.com/reference/androidx/preference/PreferenceFragmentCompat
prefChange 时监听
class SettingsFragment : PreferenceFragmentCompat()
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?)
setPreferencesFromResource(R.xml.root_preferences, rootKey)
val prefListener =
OnSharedPreferenceChangeListener prefs, key ->
val valueChanged = preferenceManager.sharedPreferences.getString(key,key)
when(valueChanged)
getString(R.string.value_lang_en) -> applyLang(valueChanged)
getString(R.string.value_lang_th) -> applyLang(valueChanged)
preferenceManager.
sharedPreferences.
registerOnSharedPreferenceChangeListener(prefListener)
【讨论】:
【参考方案2】:如果你只想更新摘要,使用androidx preference library(参见official guides),并在你的布局xml中添加以下属性就足够了:
<EditTextPreference
...
app:useSimpleSummaryProvider="true" />
【讨论】:
【参考方案3】:您只需要在onResume()
方法中删除指定的 Prefernce 类。就我而言,我使用的是SwitchPreference
类,因此代码类似于- SettingsActivity.class
public static class PrivacyPreferenceFragment extends PreferenceFragment
public SwitchPreference switchPreference;
@Override
public void onResume()
super.onResume();
switchPreference = (SwitchPreference) findPreference("privacy_notice_check");
@Override
public void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_privacy);
setHasOptionsMenu(true);
然后在要使用PrefernceFragment
值的activity中,只需使用SharedPreference
对象调用值并触发即可。
【讨论】:
【参考方案4】:我最近使用 Preferences API
完成了自己的 PreferenceScreen
组合,所以我想我会贡献我自己的完整示例。这包括将 Summary
更新为新的/更改的值,以及侦听和对更改做出反应。PS。回答您的最后一个问题:在初始创建 PreferenceScreen
时显示 Summary
的默认值(在值发生任何更改之前) ),您可以直接在preferences.xml
文件中将android:summary
设置为您选择的值 - 然后,一旦有更改值,它将使用下面我的示例中包含的代码自动更新。 个人,我使用Preference
的简短解释作为我的初始Summary
,设置在我的preferences.xml
中,然后一旦值确实 更改为第一次,它会简单地将当前值显示为 Summary
从那时起..无论如何,这是我的完整示例:SettingsFragment.java
public class SettingsFragment extends PreferenceFragment
public static final String PREF_NOTIFICATION_MODE = "pref_notificationMode";
private SharedPreferences.OnSharedPreferenceChangeListener preferenceChangeListener;
@Override
public void onCreate (@Nullable Bundle savedInstanceState)
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
final SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(this.getActivity());
preferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener()
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
if (key.equals(PREF_NOTIFICATION_MODE))
Preference notifModePref = findPreference(key);
notifModePref.setSummary(sharedPreferences.getString(key, ""));
// DO SOMETHING ELSE HERE WHEN (PREF_NOTIFICATION_MODE) IS CHANGED
;
@Override
public void onResume()
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(preferenceChangeListener);
Preference notifModePref = findPreference(PREF_NOTIFICATION_MODE);
notifModePref.setSummary(getPreferenceScreen().getSharedPreferences().getString(PREF_NOTIFICATION_MODE, ""));
@Override
public void onPause()
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(preferenceChangeListener);
super.onPause();
我希望这会有所帮助! 非常感谢任何积极的反馈,因为我是 *** 的新手 ;)编码愉快!
【讨论】:
在onPause
中,super.onPause()
应该在侦听器注销之前还是之后调用?甚至有区别吗?我在很多例子中都看到过
@BryanWalsh 我也看到了both 方式的示例。我认为在调用super.onPause();
之前 注销listerner 可能是最好的解决方法。【参考方案5】:
这是一种避免任何潜在内存泄漏的方法:
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey)
addPreferencesFromResource(R.xml.pref_movies);
SharedPreferences sharedPreferences = getPreferenceScreen().getSharedPreferences();
//starts live change listener
sharedPreferences.registerOnSharedPreferenceChangeListener(this);
@Override
public void onDestroyView ()
super.onDestroyView();
//Unregisters listener here
PreferenceManager.getDefaultSharedPreferences(getContext())
.unregisterOnSharedPreferenceChangeListener(this);
【讨论】:
【参考方案6】:另一个完整的例子,让你看到整个画面。
public class SettingsActivity extends AppCompatPreferenceActivity
/**
* A preference value change listener that updates the preference's summary
* to reflect its new value.
*/
private static Preference.OnPreferenceChangeListener
sBindPreferenceSummaryToValueListener =
new Preference.OnPreferenceChangeListener()
@Override
public boolean onPreferenceChange(Preference preference, Object value)
String stringValue = value.toString();
if (preference instanceof ListPreference)
// For list preferences, look up the correct display value in
// the preference's 'entries' list.
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
// Set the summary to reflect the new value.
preference.setSummary(
index >= 0
? listPreference.getEntries()[index]
: null);
else if (preference instanceof RingtonePreference)
// For ringtone preferences, look up the correct display value
// using RingtoneManager.
if (TextUtils.isEmpty(stringValue))
// Empty values correspond to 'silent' (no ringtone).
preference.setSummary(R.string.pref_ringtone_silent);
else
Ringtone ringtone = RingtoneManager.getRingtone(
preference.getContext(), Uri.parse(stringValue));
if (ringtone == null)
// Clear the summary if there was a lookup error.
preference.setSummary(null);
else
// Set the summary to reflect the new ringtone display
// name.
String name = ringtone.getTitle(preference.getContext());
preference.setSummary(name);
else
// For all other preferences, set the summary to the value's
// simple string representation.
preference.setSummary(stringValue);
return true;
;
/**
* Helper method to determine if the device has an extra-large screen. For
* example, 10" tablets are extra-large.
*/
private static boolean isXLargeTablet(Context context)
return (context.getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE;
/**
* Binds a preference's summary to its value. More specifically, when the
* preference's value is changed, its summary (line of text below the
* preference title) is updated to reflect the value. The summary is also
* immediately updated upon calling this method. The exact display format is
* dependent on the type of preference.
*
* @see #sBindPreferenceSummaryToValueListener
*/
private static void bindPreferenceSummaryToValue(Preference preference)
// Set the listener to watch for value changes.
preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
// Trigger the listener immediately with the preference's current value.
sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.getString(preference.getKey(), ""));
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setupActionBar();
/**
* Set up the @link android.app.ActionBar, if the API is available.
*/
private void setupActionBar()
ActionBar actionBar = getSupportActionBar();
if (actionBar != null)
// Show the Up button in the action bar.
actionBar.setDisplayHomeAsUpEnabled(true);
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item)
int id = item.getItemId();
if (id == android.R.id.home)
if (!super.onMenuItemSelected(featureId, item))
NavUtils.navigateUpFromSameTask(this);
return true;
return super.onMenuItemSelected(featureId, item);
/**
* @inheritDoc
*/
@Override
public boolean onIsMultiPane()
return isXLargeTablet(this);
/**
* @inheritDoc
*/
@Override
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void onBuildHeaders(List<Header> target)
loadHeadersFromResource(R.xml.pref_headers, target);
/**
* This method stops fragment injection in malicious applications.
* Make sure to deny any unknown fragments here.
*/
protected boolean isValidFragment(String fragmentName)
return PreferenceFragment.class.getName().equals(fragmentName)
|| GPSLocationPreferenceFragment.class.getName().equals(fragmentName)
|| DataSyncPreferenceFragment.class.getName().equals(fragmentName)
|| NotificationPreferenceFragment.class.getName().equals(fragmentName);
////////////////// NEW PREFERENCES ////////////////////////////
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class GPSLocationPreferenceFragment extends PreferenceFragment
Preference prefGPSServerAddr, prefGPSASDID, prefIsGPSSwitch;
@Override
public void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_gps_location);
setHasOptionsMenu(true);
// Bind the summaries of EditText/List/Dialog/Ringtone preferences
// to their values. When their values change, their summaries are
// updated to reflect the new value, per the Android Design
// guidelines.
bindPreferenceSummaryToValue(findPreference("gpsServer_Addr"));
bindPreferenceSummaryToValue(findPreference("gpsASD_ID"));
prefGPSServerAddr = findPreference("gpsServer_Addr");
prefGPSServerAddr.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
@Override
public boolean onPreferenceChange(Preference preference, Object newValue)
try
// do whatever you want with new value
catch (Exception ex)
Log.e("Preferences", ex.getMessage());
// true to update the state of the Preference with the new value
// in case you want to disallow the change return false
return true;
);
prefGPSASDID = findPreference("gpsASD_ID");
prefGPSASDID.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
@Override
public boolean onPreferenceChange(Preference preference, Object newValue)
try
// do whatever you want with new value
catch (Exception ex)
Log.e("Preferences", ex.getMessage());
// true to update the state of the Preference with the new value
// in case you want to disallow the change return false
return true;
);
prefIsGPSSwitch = findPreference("isGPS_Switch");
prefIsGPSSwitch.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
@Override
public boolean onPreferenceChange(Preference preference, Object newValue)
try
// do whatever you want with new value
catch (Exception ex)
Log.e("Preferences", ex.getMessage());
// true to update the state of the Preference with the new value
// in case you want to disallow the change return false
return true;
);
@Override
public boolean onOptionsItemSelected(MenuItem item)
int id = item.getItemId();
if (id == android.R.id.home)
boolean tabletSize = getResources().getBoolean(R.bool.isTablet);
if (tabletSize)
startActivity(new Intent(getActivity(), MainActivity.class));
else
startActivity(new Intent(getActivity(), SettingsActivity.class));
return true;
return super.onOptionsItemSelected(item);
///////////////////////////////////////////////////////////////
/**
* This fragment shows notification preferences only. It is used when the
* activity is showing a two-pane settings UI.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class NotificationPreferenceFragment extends PreferenceFragment
@Override
public void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_notification);
setHasOptionsMenu(true);
// Bind the summaries of EditText/List/Dialog/Ringtone preferences
// to their values. When their values change, their summaries are
// updated to reflect the new value, per the Android Design
// guidelines.
bindPreferenceSummaryToValue(findPreference("notifications_new_message_ringtone"));
@Override
public boolean onOptionsItemSelected(MenuItem item)
int id = item.getItemId();
if (id == android.R.id.home)
boolean tabletSize = getResources().getBoolean(R.bool.isTablet);
if (tabletSize)
startActivity(new Intent(getActivity(), MainActivity.class));
else
startActivity(new Intent(getActivity(), SettingsActivity.class));
return true;
return super.onOptionsItemSelected(item);
/**
* This fragment shows data and sync preferences only. It is used when the
* activity is showing a two-pane settings UI.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class DataSyncPreferenceFragment extends PreferenceFragment
@Override
public void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_data_sync);
setHasOptionsMenu(true);
// Bind the summaries of EditText/List/Dialog/Ringtone preferences
// to their values. When their values change, their summaries are
// updated to reflect the new value, per the Android Design
// guidelines.
bindPreferenceSummaryToValue(findPreference("sync_frequency"));
@Override
public boolean onOptionsItemSelected(MenuItem item)
int id = item.getItemId();
if (id == android.R.id.home)
boolean tabletSize = getResources().getBoolean(R.bool.isTablet);
if (tabletSize)
startActivity(new Intent(getActivity(), MainActivity.class));
else
startActivity(new Intent(getActivity(), SettingsActivity.class));
return true;
return super.onOptionsItemSelected(item);
【讨论】:
【参考方案7】:这对我有用 PreferenceFragment.onCreate()
OnSharedPreferenceChangeListener listener =
new SharedPreferences.OnSharedPreferenceChangeListener()
public void onSharedPreferenceChanged(SharedPreferences prefs, String key)
showDialog();
;
【讨论】:
【参考方案8】:所有其他答案都是正确的。但我更喜欢这种替代方案,因为您立即拥有导致更改的 Preference 实例。
@Override
public void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
Preference pref = findPreference(getString(R.string.key_of_pref));
pref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
@Override
public boolean onPreferenceChange(Preference preference, Object newValue)
// do whatever you want with new value
// true to update the state of the Preference with the new value
// in case you want to disallow the change return false
return true;
);
【讨论】:
正确,尽管在onSharedPreferenceChanged ()
中,您可以使用findPreference(key)
轻松访问Preference 实例。也许SharedPreferences
方式是首选,因为注册/注销的事情?【参考方案9】:
antew 的解决方案效果很好,在这里您可以看到 Android v11 及以上版本的完整偏好活动:
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.PreferenceFragment;
public class UserPreferencesV11 extends Activity
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
// Display the fragment as the main content.
getFragmentManager().beginTransaction().replace(android.R.id.content,
new PrefsFragment()).commit();
public static class PrefsFragment extends PreferenceFragment implements OnSharedPreferenceChangeListener
@Override
public void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
// set texts correctly
onSharedPreferenceChanged(null, "");
@Override
public void onResume()
super.onResume();
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
@Override
public void onPause()
super.onPause();
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
// just update all
ListPreference lp = (ListPreference) findPreference(PREF_YOUR_KEY);
lp.setSummary("dummy"); // required or will not update
lp.setSummary(getString(R.string.pref_yourKey) + ": %s");
【讨论】:
静态类中没有这个! 你能详细说明一下吗?我完全不知道你指的是哪个“这个”。答案是7岁。 Android 发生了很大变化。 public static class PrefsFragment 声明一个静态类,然后在内部使用它来引用自身。但这是不可能的,你不能在静态类中使用它。 你确定你理解Java中静态内部类的概念吗?静态嵌套类可以在不实例化其外部类的情况下进行实例化。使用“this”非常好。这不是 C#! 我不确定,但我在 Android Studio 中尝试了代码,它抱怨这个:“getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);”。我必须重写代码才能编译。【参考方案10】:我相信您只需在您的PreferenceFragment
中注册/取消注册Listener
即可。
@Override
public void onResume()
super.onResume();
getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
@Override
public void onPause()
getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
super.onPause();
根据您想要做什么,您可能不需要使用监听器。对首选项的更改会自动提交给SharedPreferences
。
【讨论】:
啊,我明白了。这样可行。但是我应该通过getPreferenceManager
(就像您所做的那样)还是getPreferenceScreen
获得SharedPreferences?有什么区别?
老实说,我不确定真正的区别是什么,也许其他人可以权衡一下,这也可能是另一个问题的好话题。
好的,here 是该问题的答案。看起来绝对没有功能上的区别,但getPreferenceManager
通常是首选。
第一次创建设置首选项时,不会根据存储的首选项值设置摘要。如何解决这个问题??
@srv_sud 你的意思是key
参数应该是什么?没试过这个,你在 Gunnar 的回答中有一个例子:onSharedPreferenceChanged(null, "")
。它可能不适合您的需求。也许您应该迭代需要更新的偏好键以上是关于如何监听 PreferenceFragment 中的偏好变化?的主要内容,如果未能解决你的问题,请参考以下文章
如何在Fragment中使用PreferenceFragment
如何在Fragment中使用PreferenceFragment
我们如何使用 espresso 来测试带有 PreferenceFragment 的 android 设置活动?