Enables horizontal and portrait screen switching for Android phones.
In Android, when the screen is switched horizontally or vertically, the lifecycle of the Activity is re-loaded (indicating that the current Activity has been destroyed but loaded again ),
How can I prevent the current Activity from being destroyed when the screen is switched horizontally or vertically?
1. Set the configChanges attribute for the Activity IN AndroidManifest. xml,
application android:icon="@drawable/icon" android:label="@string/app_name"><activity android:name=".MainActivity" android:label="@string/app_name" android:configChanges="orientation|keyboardHidden"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter></activity></application>
ConfigChanges has the following options:
1. orientation: the screen rotates vertically and horizontally. keyboardHidden: displays or hides the keyboard. fontScale: the user changed the preferred font size. 4. locale: You have selected different language settings. keyboard: the keyboard type is changed. For example, the mobile phone is switched from 12 to the full keyboard. 6. touchscreen or navigation: the keyboard or navigation mode changes,
If the keyboardHidden option is missing, the Activity cannot be destroyed. In the onConfigurationChanged event mentioned later, only the vertical screen to horizontal screen can be captured.
2. Rewrite the onConfigurationChanged method in the corresponding Activity:
Public class MainActivity extends Activity {private TextView textView; @ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); Log. I ("-- Main --", "onCreate"); textView = (TextView) findViewById (R. id. TV _id) ;}@ Override public void onConfigurationChanged (Configuration newConfig) {super. onConfigurationChanged (newConfig); Log. I ("-- Main --", "onConfigurationChanged"); if (newConfig. orientation = Configuration. ORIENTATION_LANDSCAPE) {textView. setText ("current screen is landscape");} else {textView. setText ("current screen is portrait ");}}}
The effect is as follows:
Log printing:
The log shows that the Activity is not destroyed when the screen is switched horizontally or vertically. Of course, you can run the project to break a breakpoint in the onCreate method, the onCreate method is only executed when the onCreate method is started. The onConfigurationChanged method can be clicked because the onCreate method is no longer executed when the screen is switched horizontally and vertically!
Note: If the project does not require screen switching, you can set it
1. android: screenOrientation = "portrait" is always displayed on the portrait Screen
2. android: screenOrientation = "landscape" is always displayed on a horizontal screen