最佳答案
如 给你所述,我对 PreferenceFragment 进行了子类化,并将其显示在一个 Activity 中。该文档解释了如何监听首选项更改 给你,但只有在子类化 PreferenceActivity 的情况下才能监听。既然我没有这样做,那么我如何监听偏好的变化呢?
我曾经尝试在我的 PreferenceFragment 中实现 OnSharedPreferenceChangeListener,但是它似乎不起作用(onSharedPreferenceChanged
似乎从来没有被调用过)。
到目前为止,这是我的代码:
设置 Activity.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();
}
}
设置片段.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, ""));
}
}
}
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 中进行监听?