0

我找不到一个简单的解决方案来避免我的 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 显示来自“原始”文件夹的随机图像)。我正在使用的代码的简化版本是这样的:

rawClass = R.raw.class;

fields = rawClass.getFields();

rand = new Random();

rndInt = rand.nextInt(fields.length);

resID = fields[rndInt].getInt(rawClass);

imageSwitcher.setImageResource(resID);

先感谢您

4

2 回答 2

0

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

        android:configChanges="keyboardHidden|orientation|screenSize"/>
于 2018-09-21T13:37:23.557 回答
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!:

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

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

在 OnRestoreIntanceState() 方法中。

现在一切正常!

于 2017-12-20T08:58:41.100 回答