[英]Android and onSaveInstance and Restore
我有一个大问题。 我有一个活动,其中有两个imageViews。 在onCreate中,我有列出图片,其中有10张图片。 每次启动此活动时,两个imageViews都会从List中获取随机图片并显示它们。 例如:当我开始活动时,我可以看到汽车和铅笔,当我再次开始此活动时,我得到了大象和书本。 现在这是我的问题。 当我开始活动并阻止手机时,解锁后我会得到其他照片。 我认为onCreate被再次调用。 我创造
@Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
}
public void onRestoreInstanceState(Bundle savedInstanceState) {
if (savedInstanceState != null) {
pictureGameLeft.setImageResource(shapesPictures.get(game.getCurrentLevel().getCurrentPair().getImageLeft()));
pictureGameRight.setImageResource(shapesPictures.get(game.getCurrentLevel().getCurrentPair().getImageRight()));
}
}
pictureGameLeft和Right是最后显示的图像。 我在onCreate方法之后编写它们。 如何保存上次查看的图片,如果我锁定和解锁手机,我会得到相同的图片。 也许onPause或onStop需要调用?
编辑:现在:
if (savedInstanceState == null) {
game = new Game();
game.initGame();
addElements(result);
game.getCurrentLevel().nextPair();
pictureGameLeft.setImageResource(shapesPictures.get(game.getCurrentLevel().getCurrentPair()
.getImageLeft()));
pictureGameRight.setImageResource(shapesPictures.get(game.getCurrentLevel().getCurrentPair()
.getImageRight()));
mRedrawHandler.sleep(1000);
}
else {
pictureGameLeft.setImageResource(shapesPictures.get(game.getCurrentLevel().getCurrentPair(
.getImageLeft()));
pictureGameRight.setImageResource(shapesPictures.get(game.getCurrentLevel().getCurrentPair()
.getImageRight()));
}
但是我得到了NullPointerException。
在做出决定的那一刻,我会将当前选择的图片保存到首选项中。 比起您不必摆弄实时循环方法。
决定何时从偏好中选择选项或创建新(随机)选项的决定很容易。 只要检查一下
savedInstanceState
的
public void onCreate (Bundle savedInstanceState)
一片空白。 如果是这样,这是第一个电话。 后续的重新打开具有非空值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.