我无法找到一个简单的解决方案来避免我的ImageSwitcher更改旋转屏幕时显示的ImageResource。我尝试在onSaveInstanceState()和onRestoreInstanceState()中编写不同的东西,但我找不到任何有用的东西。
我怎样才能实现这样的目标(纯伪代码):
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
int picNum = imageSwitcher.getImageResource();
savedInstanceState.putInt("picNum", picNum);
// etc.
super.onSaveInstanceState(savedInstanceState);
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
Int picNum = savedInstanceState.getString("picNum");
imageSwitcher.setImageResource(picNum);
}
我不确切知道所显示的图像名称,所以每次都必须找到它(每次ImageSwitcher都会显示“raw”文件夹中的随机图像)。我正在使用的代码的简化版本是:
rawClass = R.raw.class;
fields = rawClass.getFields();
rand = new Random();
rndInt = rand.nextInt(fields.length);
resID = fields[rndInt].getInt(rawClass);
imageSwitcher.setImageResource(resID);
提前谢谢
答案 0 :(得分:0)
我找到了解决方法:
我将resId存储在int []中,我可以将其称为switcherImageView.setImageResource(imgArr[currentPhoto]);
之后我也可以在saveonSaveInstanceState()方法中使用它:
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save UI state changes to the savedInstanceState.
int randInteger = rndInt;
int[] saveArray = imgArr;
int picNum = imgArr[currentPhoto];
savedInstanceState.putInt("picNum", picNum);
savedInstanceState.putInt("randInteger", randInteger);
savedInstanceState.putIntArray("picArr", saveArray);
// etc.
super.onSaveInstanceState(savedInstanceState);
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
int[] picArr = savedInstanceState.getIntArray("picArr");
int picNum = savedInstanceState.getInt("picNum");
imgArr = picArr;
imageSwitcher.setImageResource(picNum);
}
现在,当我旋转屏幕时,一切都很好,我可以在ImageSlider中使用相同的图片
的但强>
当我再次点击时,它与索引的关系并不重要,它将从数组imgArr[0]
的最开头开始。
修改强> 找到最终解决方案! :)我必须明确地存储索引:doh!:
所以我写道:
onSaveInstanceState()方法中的int currentPhoto= indexNumber;
savedInstanceState.putInt("currentPhoto", currentPhoto);
和
int photoCurrent = savedInstanceState.getInt("currentPhoto");
在OnRestoreIntanceState()方法中。
现在一切正常!
答案 1 :(得分:0)
您还可以在清单文件中添加以下行。
android:configChanges="keyboardHidden|orientation|screenSize"/>