Resolve the Android horizontal portrait switch

  • 2020-05-10 18:52:00
  • OfStack

In the development of android, when the screen changes from portrait to landscape by default, the onConfigurationChanged event will be triggered. By default, the screen will be reloaded and the same screen will be displayed. There will be two problems.
With vertical layout problem, the layout of the screen to landscape changed due to the width and height of all how much will affect the layout (unless you customize the 2 sets of images and then add a judgement how to display in landscape, how in vertical screen display), of course, the simplest way is in the project AndroidManifest. Find you specified activity xml add
For portrait only (android:screenOrientation="portrait")
Landscape only (android:screenOrientation="landscape")
Reload the picture problem: by default, namely changes will reload the screen, lead to more unnecessary waste of resources, more serious is the picture to keep the data (especially games) also are reset (of course, you can save these data into the database before the reset or to a text file), how to avoid in the relation when switching to reload the picture,
The first thing to do is to find the AndroidManifest.xml you specify activity plus android:configChanges="orientation|keyboardHidden"
Then, in the logical processing of activity (the code part), overload the onConfigurationChanged event. For the specific code, please refer to the following code:  

@Override
    public void onConfigurationChanged(Configuration config) { 
        try { 
            super.onConfigurationChanged(newConfig); 
            if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { 
  // The code to work with when landscape,  
  // The code here is to view the screen as portrait when it is landscape                
  setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); 
            } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { 
   // The code to work with when portrait  
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); 

            } 
        } catch (Exception ex) { 
        } 
    }

Above, you can simply control the display mode of your app screen and do not reload the screen when switching between horizontal and vertical screens without changing the display mode. In other words, you can optimize your app and improve your user experience accordingly.
Above, hope to help you. Ha ha.

Related articles: