onSharedPreferenceChanged未被调用,我使用以下代码:
compile 'net.sourceforge.htmlunit:htmlunit:2.22'
pref.xml
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings2);
getFragmentManager().beginTransaction().replace(android.R.id.content, new Frag()).commit();
}
public static class Frag extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref);
getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
System.out.println(key);
}
}
当我更改SwitchPreference时,它没有调用onSharedPreferenceChanged,为什么?
答案 0 :(得分:0)
代码SwitchPreference没有设置android:key:
<SwitchPreference android:title="show floating touch" android:defaultValue="false"></SwitchPreference>
将其更改为:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<SwitchPreference android:key="show_float_toucher" android:title="show floating toucher" android:defaultValue="false"/>
</PreferenceScreen>
工作
答案 1 :(得分:0)
我发现有同样问题的以下链接很有用:
How to listen for preference changes within a PreferenceFragment?
代码示例:
public class PrefActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new PrefFragment()).commit();
}
public static class PrefFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
@Override
public void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
@Override
public void onPause() {
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
super.onPause();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set xml
addPreferencesFromResource(R.xml.pref);
// set texts correctly
onSharedPreferenceChanged(null, "");
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals("show_float_toucher"))
{
//TODO
}
}
}
}
提示:检查你minSdkVersion!
最好的问候!