Some netizens will find that the Activity is switched to the background or the layout is switched from LANDSCAPE screen LANDSCAPE to PORTRAIT. Switching the Activity again will trigger an onCreate method. We can go to androidmanifest. add the activit element in xml to this attribute Android: configChanges = "orientation | keyboardHidden", for example
<Activity android: name = ". android123" android: configChanges = "orientation | keyboardHidden" android: label = "@ string/app_name">
Java code
Copy codeThe Code is as follows:/* declare the Display object to get the screen width and height */
Final Display defaultDisplay = getWindow (). getWindowManager ()
. Getdefadisplay display ();
IntScreenH = defaultDisplay. getHeight ();
IntScreenW = defaultDisplay. getWidth ();
/* If it is Landscape */
If (intScreenW> intScreenH)
{
/* Landscape => Portrait */
SetRequestedOrientation (ActivityInfo. SCREEN_ORIENTATION_PORTRAIT );
} Else
{
/* Portrait => Landscape */
SetRequestedOrientation (ActivityInfo. SCREEN_ORIENTATION_LANDSCAPE );
}
/* Declare the Display object to get the screen width and height */
Final Display defaultDisplay = getWindow (). getWindowManager ()
. Getdefadisplay display ();
IntScreenH = defaultDisplay. getHeight ();
IntScreenW = defaultDisplay. getWidth ();
/* If it is Landscape */
If (intScreenW> intScreenH)
{
/* Landscape => Portrait */
SetRequestedOrientation (ActivityInfo. SCREEN_ORIENTATION_PORTRAIT );
} Else
{
/* Portrait => Landscape */
SetRequestedOrientation (ActivityInfo. SCREEN_ORIENTATION_LANDSCAPE );
}
At the same time, the onConfigurationChanged (Configuration newConfig) method is reloaded in the Java file of the Activity, so that the onCreate method is not reloaded during layout switching or window switching. The Code is as follows:
Java codeCopy codeThe Code is as follows: @ Override
Public void onConfigurationChanged (Configuration newConfig)
{
Super. onConfigurationChanged (newConfig );
If (this. getResources (). getConfiguration (). orientation = Configuration. ORIENTATION_LANDSCAPE)
{
// Land
}
Else if (this. getResources (). getConfiguration (). orientation = Configuration. ORIENTATION_PORTRAIT)
{
// Port
}
}
@ Override
Public void onConfigurationChanged (Configuration newConfig)
{
Super. onConfigurationChanged (newConfig );
If (this. getResources (). getConfiguration (). orientation = Configuration. ORIENTATION_LANDSCAPE)
{
// Land
}
Else if (this. getResources (). getConfiguration (). orientation = Configuration. ORIENTATION_PORTRAIT)
{
// Port
}
}