1
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. 再次从其图标激活我的应用程序

我看到我的切换按钮未选中,为什么会这样?我该如何克服呢?

4

2 回答 2

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));
    }
}
于 2012-09-08T23:11:16.887 回答
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));
    }
}
于 2012-09-08T22:54:10.990 回答