旋转屏幕时,如何从ImageSwitcher中保存ImageResource



我找不到一个简单的解决方案来避免我的images开机更改旋转屏幕时显示的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);

预先感谢您

我找到了一个解决方法:

我将残基存储在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!:

所以我写道: int currentPhoto= indexNumber; savedInstanceState.putInt("currentPhoto", currentPhoto);在OnSaveInstanceState()方法中和

int photoCurrent =  savedInstanceState.getInt("currentPhoto");

在OnrestoreIntancestate()方法中。

现在一切都起作用!

您还可以将以下行放入清单文件中。

        android:configChanges="keyboardHidden|orientation|screenSize"/>

相关内容

  • 没有找到相关文章

最新更新