Resource update after changing screen orientation

To avoid running onCreate () again when the screen orientation changes, I put the following in the Android manifest:

android:configChanges="orientation|keyboardHidden|screenSize" 

It's good. However, I still want to be able to rotate the screen just by changing the orientation, but DO NOT go back to the onCreate-> onStart-> etc. life cycle.

I tried the onConfigurationChanged method as follows:

 @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); } 

And it works great. However, I have a background image that needs to be changed depending on whether 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 is to reload the splash_bg resource now that the orientation has changed, so it will look in a drawable folder for the image.

So now the method is as follows:

 @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); mBackground.setBackgroundResource(R.drawable.splash_bg); } 

But this does not work perfectly right. After the initial launch of the device, say, in portrait mode, the background image of the portrait is displayed. Turning it (in landscape mode), you will successfully change the background image from the background of the portrait to the landscape background (the one that is on the painted earth). The converse is also true (if you start with a landscape and switch to a portrait), because I also included the version of portraying the background image in a folder with a dedicated port (on top of a folder with easy output).

Thus, with the initial rotation, it works great. But if you switch the BACK orientation to the initial one, it will not update the image to its correct orientation type. Basically, it only works once.

Does anyone have an idea? If necessary, I provided more code, but I think I included everything I needed. Thanks!

+4
source share
2 answers

First, do not use configChanges . This is a lazy way out and ultimately bites you in the future. Drawables are cached, so this probably causes problems with getting the right image for orientation (which explains why it works once, but not after). You can get around this by having two highlighted lines: one named splash_bg_port, one named splash_bg_land, and use them by switching the orientation you get from newConfig .

Also, if your splash_bg is a list of layers with bitmap elements, I noticed that sometimes it is not pulled from the correct resource folders (due to caching) after the first access to the extracted one.

+3
source

Does this check this.

 @Override public void onConfigurationChanged(Configuration newConfig) { mBackground.setBackgroundResource(R.drawable.splash_bg); super.onConfigurationChanged(newConfig); } 
+1
source

Source: https://habr.com/ru/post/1501748/


All Articles