保留我的活动上的切换按钮状态

时间:2012-09-08 22:29:55

标签: android togglebutton

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);
}

它似乎应该可以工作,但是如果我执行以下操作:

  1. 通过应用程序菜单上的图标运行我的应用程序
  2. 检查切换按钮
  3. 按后退按钮
  4. 返回主屏幕
  5. 再次从其图标激活我的应用程序
  6. 我看到我的切换按钮未选中,为什么会这样?我该如何克服这个?

2 个答案:

答案 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));
    }
}