SharedPreference更改侦听器和自定义首选项

时间:2014-11-18 22:26:26

标签: android settings listener shared preference

我有这些偏好:

<xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<CheckBoxPreference
    android:key="pk1"
    android:title="@string/pt1"
    android:summary="@string/pt1s"
    android:defaultValue="false" />
<CheckBoxPreference
    android:key="pk2"
    android:title="@string/pt2"        
    android:defaultValue="false" />
<ListPreference 
    android:key="pk3"
    android:title="@string/pt3"
    android:dialogTitle="@string/pt3"
    android:entries="@array/fontsi"
    android:entryValues="@array/fontsiv"
    android:defaultValue="0" />     
<Preference
android:key="pkb"
android:title="@string/ptb" />
</PreferenceScreen>

设置活动:

public class SettingsActivity extends PreferenceActivity {
SharedPreferences.OnSharedPreferenceChangeListener lst;
SharedPreferences prf;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);
    prf = getPreferenceScreen().getSharedPreferences();
    lst = new SharedPreferences.OnSharedPreferenceChangeListener() {
    public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
    Log.i("SettingsActivity","!any preference changen!");
    if (key.equals("pk1")) { Log.i("SettingsActivity","!pref PK1 called!"); }                                            }  
    else if (key.equals("pkb")) { Log.i("SettingsActivity","!pref PKB called!"); }            
    prf.registerOnSharedPreferenceChangeListener(lst);
}

@Override
protected void onResume() {
    super.onResume();
    prf.registerOnSharedPreferenceChangeListener(lst); }

@Override
protected void onPause() {
    super.onPause();
    prf.unregisterOnSharedPreferenceChangeListener(lst); }
...    
}

侦听器使用所有首选项但是自定义首选项(最后一个,pkb作为键)! 我想用作后退按钮。 谁知道为什么?

1 个答案:

答案 0 :(得分:2)

显然,您的偏好不会改变任何偏好。

由于它没有做任何事情,OnSharedPreferenceChangeListener会忽略它。

一种可能的解决方案是像这样设置clickListener

findPreference("pkb").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
    @Override
    public boolean onPreferenceClick(Preference preference) {
        Log.i("SettingsActivity", "!pref PKB called!");
        return false;
    }
});