在onSaveInstanceState中保存图像按钮的isSelected()属性并将其恢复

时间:2014-08-07 13:15:36

标签: java android

假设我有一个图像按钮,更改图像onClick(),因此isSelected()属性为true。如何在onSaveInstanceState()中保存此属性,以便以后可以在旋转手机时将其恢复?

1 个答案:

答案 0 :(得分:2)

首先,将isSelected()属性保存在onSaveInstanceState()

public final String STATE_SELECTED = "state_selected";

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    super.onSaveInstanceState(savedInstanceState);
    savedInstanceState.putBoolean(STATE_SELECTED, button.isSelected());
}

然后在onRestoreInstanceState()

中访问并使用此值
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    boolean selected = savedInstanceState.getBoolean(STATE_SELECTED);
    button.setSelected(selected);
    if (selected) // Do some stuff
    else //Do some other stuff
}

希望这有帮助!

编辑:在回复您的评论时,以下是按钮数组的执行方式:

public final String STATE_SELECTED = "state_selected";
public Button[] buttons; // This is populated elsewhere

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    super.onSaveInstanceState(savedInstanceState);
    boolean[] selected = new boolean[buttons.length];
    for (int i = 0; i < buttons.length; i++) selected[i] = buttons[i].isSelected();
    savedInstanceState.putBooleanArray(STATE_SELECTED, selected);
}

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    boolean[] selected = savedInstanceState.getBooleanArray(STATE_SELECTED);
    for (int i = 0; i < buttons.length; i++) button[i].setSelected(selected[i]);
}