我目前正在开发一个具有菜单的应用程序,菜单上的一个选项是“设置”,用户基本上可以决定关闭声音和其他类似的东西.我目前在“设置”活动中有两个开关.到目前为止,这是Settings活动的
java代码:
import android.support.v7.app.ActionBarActivity; public class Options extends ActionBarActivity { private Switch ding; private Switch countdown; public boolean isDingChecked; public boolean isCountdownChecked; public static final String PREFS = "examplePrefs"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_options); ding = (Switch) findViewById(R.id.switch1); ding.setOnCheckedChangeListener(new OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) { SharedPreferences examplePrefs = getSharedPreferences(PREFS,0); Editor editor = examplePrefs.edit(); editor.putBoolean("userMessage",isChecked); editor.commit(); //System.out.println(examplePrefs.getBoolean("userMessage",isChecked)); isDingChecked = examplePrefs.getBoolean("userMessage",isChecked); System.out.println(isDingChecked + " is ding checked"); ding.setChecked(isDingChecked); } }); countdown = (Switch) findViewById(R.id.switch2); countdown.setOnCheckedChangeListener(new OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) { // do something,the isChecked will be // true if the switch is in the On position isCountdownChecked = isChecked; } }); } }
我可以在我的其他活动中使用布尔值,因此SharedPreference工作正常.但是,当我返回到菜单活动并返回到此选项活动时,无论用户声明什么,开关的状态都会恢复为默认值true.无论如何我可以解决这个问题吗?
ding.setChecked(isDingChecked)
我猜不是真的做了什么.我知道我过去发过一个类似的问题,只是一个人没有太多的活动,我已经在这个问题上工作了很长一段时间.谢谢!
解决方法
尝试这样的事情:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_options); ding = (Switch) findViewById(R.id.switch1); //grab prefs first final SharedPreferences examplePrefs = getSharedPreferences(PREFS,0); final Editor editor = examplePrefs.edit(); ding.setChecked(examplePrefs.getBoolean("your_key",false)); //false default ding.setOnCheckedChangeListener(new OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) { //commit prefs on change editor.putBoolean("your_key",isChecked); editor.commit(); System.out.println(isDingChecked + " is ding checked"); } });