public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.some_layout);
toggleButton=(ToggleButton) findViewById(R.id.toggleButton1);
}
@Override
public void onSaveInstanceState(Bundle save) {
super.onSaveInstanceState(save);
save.putBoolean("ToggleButtonState", toggleButton.isChecked());
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
toggleButton.setChecked(savedInstanceState.getBoolean("ToggleButtonState",false);
}
它似乎应该可以工作,但是如果我执行以下操作:
我看到我的切换按钮未选中,为什么会这样?我该如何克服这个?
答案 0 :(得分:4)
我错过了保存和恢复方法的用途,但为了实现我正在寻找的功能,我做了以下操作:
public class MainActivity extends Activity {
private ToggleButton toggleButton;
private static Bundle bundle = new Bundle();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toggleButton = (ToggleButton)findViewById(R.id.toggleButton1);
}
@Override
public void onPause() {
super.onPause();
bundle.putBoolean("ToggleButtonState", toggleButton.isChecked());
}
@Override
public void onResume() {
super.onResume();
toggleButton.setChecked(bundle.getBoolean("ToggleButtonState",false));
}
}
答案 1 :(得分:0)
这是我的代码
package com.example.stackoverflow;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ToggleButton;
public class MainActivity extends Activity {
ToggleButton toggleButton;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toggleButton = (ToggleButton)findViewById(R.id.toggleButton1);
}
@Override
public void onSaveInstanceState(Bundle save) {
super.onSaveInstanceState(save);
save.putBoolean("ToggleButtonState", toggleButton.isChecked());
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
toggleButton.setChecked(savedInstanceState.getBoolean("ToggleButtonState",false));
}
}