问题描述
由于这里描述,我继承preferenceFragment和里面显示出来一个活动。该文件解释了如何为preference变化这里听,但前提是你子preferenceActivity。因为我没有那样做,我怎么听preference变化?
As described here, I am subclassing PreferenceFragment and displaying it inside an Activity. That document explains how to listen for preference changes here, but only if you subclass PreferenceActivity. Since I'm not doing that, how do I listen for preference changes?
我试着在我的preferenceFragment实施OnShared preferenceChangeListener但它似乎没有工作( onShared preferenceChanged
似乎永远不会被调用)。
I've tried implementing OnSharedPreferenceChangeListener in my PreferenceFragment but it does not seem to work (onSharedPreferenceChanged
never seems to get called).
这是我的code到目前为止:
This is my code so far:
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甚至在正确的地方来监听preference变化或者我应该在活动中做到这一点?
Also, is the PreferenceFragment even the right place to listen for preference changes or should I do it within the Activity?
推荐答案
我相信,你只需要注册/注销监听器
在 preferenceFragment
,它会工作。
I believe you just need to register/unregister the Listener
in your PreferenceFragment
and it will work.
@Override
public void onResume() {
super.onResume();
getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
@Override
public void onPause() {
getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
super.onPause();
}
根据你想做的事,你可能不需要使用监听器的东西。更改为preferences致力于共享preferences
自动。
这篇关于如何监听中的preferenceFragment preference变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!