gpt4 book ai didi

java - 在 onSaveInstanceState 中保存图像按钮的 isSelected() 属性并恢复它

转载 作者:行者123 更新时间:2023-11-29 21:03:42 37 4
gpt4 key购买 nike

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

最佳答案

首先,将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]);
}

关于java - 在 onSaveInstanceState 中保存图像按钮的 isSelected() 属性并恢复它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25183571/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com