Reputation: 15740
To avoid running onCreate() over again when the screen orientation changes, I have put the following into my Android manifest:
android:configChanges="orientation|keyboardHidden|screenSize"
That's fine. However I still want to be able to rotate the screen, just having the orientation change but NOT go through the onCreate->onStart->etc life cycle again.
I overrode the method onConfigurationChanged like this:
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
And that works fine. However, I have a background image which needs to change depending on if the device is in portrait mode or landscape mode. I tried adding the following line to my code:
mBackground.setBackgroundResource(R.drawable.splash_bg);
The goal of this is to reload the splash_bg resource now that the orientation has changed, so it will look in the drawable-land folder for the image.
So the method now looks like this:
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mBackground.setBackgroundResource(R.drawable.splash_bg);
}
But it doesn't work quite right. After initially launching the device in, say, portrait mode, the portrait background image displays. Rotating it (into landscape mode) will successfully change the background image from the portrait background to the landscape background (the one found in drawable-land). The reverse is also true (if you start from landscape and switch to portrait), because I have also included the portrait mode version of the background image in the drawable-port folder (on top of the plain ol' drawable folder).
So on the initial rotation it works fine. But, if you switch the orientation BACK to where you started, it will not refresh the image to its proper orientation type. Basically it only works once.
Anyone have an idea on this? I'll provide more code if necessary but I think I included all that's needed. Thanks!
Upvotes: 4
Views: 2341
Reputation: 11324
Does this works check it
@Override
public void onConfigurationChanged(Configuration newConfig) {
mBackground.setBackgroundResource(R.drawable.splash_bg);
super.onConfigurationChanged(newConfig);
}
Upvotes: 1
Reputation: 134714
Firstly, don't use configChanges
. That's the lazy way out and will end up biting you in the future. Drawables are cached, so it's likely that this is causing issues with getting the proper image for the orientation (which would explain why it works once but not after). You could get around this by having two drawables -- one named splash_bg_port, one named splash_bg_land, and use those, switching on the orientation you receive from newConfig
.
Also, if your splash_bg is a layer-list with bitmap items, I've noticed that sometimes it doesn't pull from the correct resource folders (due to caching) after the first time you access the drawable.
Upvotes: 3