我目前正在開發一個具有菜單的應用程序,菜單上的一個選項是「設置」,用戶可以基本上決定關閉聲音和其他類似的東西。我目前在設置活動中有兩個開關。以下是目前設置活動的java代碼:更改Android開關狀態
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)
是不是真的在做我猜的任何事情。我知道我過去發佈過類似的問題,只是一個人沒有太多的活動,我在這個問題上已經研究了很長時間。謝謝!
感謝了! – user2677095 2014-09-20 09:04:10