android horizontal portrait switch does not restart the activity solution

  • 2020-05-07 20:23:11
  • OfStack

Some netizens will find that when Activity switches to the background or layout from landscape LANDSCAPE to PORTRAIT, Activity will be switched again and onCreate will be triggered once. We can add this attribute Android:configChanges="orientation|keyboardHidden" in androidmanifest.xml activit element
< activity android:name=".android123" android:configChanges="orientation|keyboardHidden" android:label="@string/app_name" >
Java code
 
/*  The statement Display Object to get the screen width and height  */ 
final Display defaultDisplay = getWindow().getWindowManager() 
.getDefaultDisplay(); 

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); 
} 
/*  The statement Display Object to get the screen width and height  */ 
final Display defaultDisplay = getWindow().getWindowManager() 
.getDefaultDisplay(); 
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); 
} 

Also override the onConfigurationChanged(Configuration newConfig) method in the Java file of Activity, so that you don't override the onCreate method in layout switching or window switching. The code is as follows:
Java code
 
@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 
} 
} 

Related articles: