当我单击“设置”页面时,我的 CheckBoxPreference 会在此阶段准确显示我想要的方式,但是当我选择它时,状态不会改变(即从未选中到选中)。
它似乎保留了 false (默认)的值,并且仍然以 false 作为传递的值运行 onPreferenceChanged。我在我的 onPreferenceChangedListener 中运行代码,该代码取决于更改的首选项的值。就目前而言,我在这里只有一个偏好。
activity_preferences.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceScreen>
<CheckBoxPreference
android:summaryOn="true"
android:summaryOff="false"
android:key="isReg"
android:title="Receive Push Messages"
android:selectable="true"
android:enabled="true"
android:persistent="true" />
</PreferenceScreen>
</PreferenceScreen>
PrefsActivity.java:
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceActivity;
import com.google.android.gcm.GCMRegistrar;
public class PrefsActivity extends PreferenceActivity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.activity_preferences);
Preference isReg = (Preference) findPreference("isReg");
isReg.setOnPreferenceChangeListener(new OnPreferenceChangeListener(){
public boolean onPreferenceChange(Preference pref, Object arg1) {
boolean isReg = getSharedPreferences("PREFERENCE", MODE_PRIVATE).getBoolean("isReg", false);
if (isReg){
ServerUtilities.register(getApplicationContext(), GCMRegistrar.getRegistrationId(getApplicationContext()));
}
else {
ServerUtilities.unregister(getApplicationContext(), GCMRegistrar.getRegistrationId(getApplicationContext()));
}
return isReg;
}
});
}
}