正如here所述,我將PreferenceFragment繼承並在Activity中顯示它。該文件解釋瞭如何傾聽偏好更改here,但僅限於PreferenceActivity的子類。由於我沒有這樣做,我如何傾聽偏好變化?如何傾聽PreferenceFragment中的偏好更改?
我試過在我的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是否適合傾聽偏好更改,或者我應該在活動內部執行嗎?
對於你最後的問題,這一切都取決於你的設計框架。要使用MVC或MVP方法很難處理Android,但我嘗試讓所有操作都發生在託管該片段的活動(Controller)中,並且片段僅作爲UI(查看/演示者) –