I can't find a simple solution to avoid my ImageSwitcher change the ImageResource displayed when I rotate the screen. I tried and tried to write different things in onSaveInstanceState() and onRestoreInstanceState(), but I couldn't find anything that works.
How can I achieve something like this (pure pseudo-code):
@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);
}
I don't know exactly the displayed image name, so I have to find it everytime (everytime the ImageSwitcher displays a random image from "raw" folder). A simplified version of the code I'm using is this:
rawClass = R.raw.class;
fields = rawClass.getFields();
rand = new Random();
rndInt = rand.nextInt(fields.length);
resID = fields[rndInt].getInt(rawClass);
imageSwitcher.setImageResource(resID);
Thank you in advance
I found a workaround:
I store the resId in on int[] and with that I can call it
switcherImageView.setImageResource(imgArr[currentPhoto]);after that I'm able to use it also in saveonSaveInstanceState() method:
Now when I rotate screen everything is fine, I can have the same pic in the ImageSlider But when I click again, it doesn't matter at what index it is, it will start from the very beginning of the array
imgArr[0].EDIT Found the final solution! :) I had to store the index obviously :doh!:
so I wrote:
int currentPhoto= indexNumber; savedInstanceState.putInt("currentPhoto", currentPhoto);in onSaveInstanceState() method andin OnRestoreIntanceState() method.
Everything works now!