search
HomeJavajavaTutorialAndroid Activity horizontal and vertical screen switching life cycle

Preface

In development, we often have to deal with horizontal and vertical screen switching. How to deal with it depends on the life cycle first

Declaration

Activity needs to call back two functions when switching between horizontal and vertical screens, so Here, these two functions are temporarily regarded as part of the life cycle of Activity horizontal and vertical screen switching. These two functions are as follows

onSaveInstanceState(Bundle outState) :Activity 即将销毁时保存数据
onRestoreInstanceState(Bundle savedInstanceState) : Activity 重建或者恢复时候取出数据

Horizontal and vertical screen switching life cycle

1. Start the program and enter the Activity interface

Android Activity 横竖屏切换的生命周期

2. Rotate the screen

Android Activity 横竖屏切换的生命周期

3. Again Rotate the screen

4 Set

android:configChanges="orientation|screenSize" in AndroidManifest.xml. Screen switching will not re-call each life cycle, but will only execute the onConfigurationChanged method

Android Activity 横竖屏切换的生命周期

Note:

When MiniSdkVersion is greater than or equal to 13: android:configChanges="orientation" or android:configChanges="orientation|keyboardHidden" Recall each life cycle

MiniSdkVersion is less than 13:

(1) When the android:configChanges of the Activity is not set, each life cycle will be re-called when switching the screen. It will be executed once when switching the horizontal screen, and twice when switching the vertical screen. Times

(2) When setting the Activity's android:configChanges="orientation", each life cycle will still be called again when switching screens. When switching to horizontal or vertical screens, it will only be executed once

(3 ) When setting the Activity's android:configChanges="orientation|keyboardHidden", switching the screen will not re-call each life cycle, and will only execute the onConfigurationChanged method

5. Avoid screen switching and restart the Activity life cycle

From the above screen switching life cycle, we can see that each switch is re-created. In order to avoid unnecessary troubles such as video playback screen rotation, etc., it is a better solution to avoid repeating the life cycle

(1) Versions before android 2.3 android:configChanges="orientation|keyboardHidden"

(2) Versions after android 3.0 android:configChanges="orientation|screenSize"

horizontal and vertical screen settings

Android horizontal and vertical screen switching is relatively common in mobile phone development. In order to avoid unnecessary trouble when switching between horizontal and vertical screens during the development process, many software usually prohibits switching between horizontal and vertical screens.

1. Set the android:screenOrientation attribute value in the activity in AndroidManifest.xml to achieve this.

(1) Vertical screen: android:screenOrientation="portrait"

(2) Horizontal screen: android:screenOrientation="landscape"

2. In Java code Set it with code similar to the following (this method is not recommended, it will be slow when starting a large app in different directions)

(1) Vertical screen: setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)

(2 ) Horizontal screen: setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)

3. If you want to completely prohibit flipping and ignore the switching caused by gravity induction, (it does not work on the simulator, it is correct on the real machine)

(1) Ignore gravity: android:screenOrientation="nosensor"

Horizontal and vertical screen recognition

1. Determine in onConfigurationChanged. In order for onConfigurationChanged to be effective in monitoring screen orientation changes, the following conditions are required

(1) AndroidManifest.xml adds permissions:

(2) AndroidManifest.xml The MiniSdkVersion and TargetSdkVersion attributes set in are greater than or equal to 13

(3) Add: android:configChanges="keyboard|screenSize|orientation|layoutDirection"

(4) in the Activity of AndroidManifest.xml Make a judgment in onConfigurationChanged(Configuration newConfig)

@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if(newConfig.orientation == 1)//竖屏
if(newConfig.orientation == 2)// 横屏
}

2. Because when the screen changes to horizontal screen, the system will re-call the Activity's onCreate method, which can be in onCreate to check the current direction, and then let your setContentView load different layout xml.

if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE){
Log.i("info","landscape"); // 横屏
} else if(this.getResources().getConfiguration().orientation ==Configuration.ORIENTATION_PORTRAIT) {
Log.i("info","portrait"); // 竖屏
}

Note: This method requires not setting onConfigurationChanged in AndroidManifest.xml to restart the life cycle

Switching layout file settings between horizontal and vertical screens

If you want the software to switch between horizontal and vertical screens, different layouts may be required because the height and width of the horizontal and vertical screens will change. You can switch the layout through the following methods

(1) Create layout-land and layout-port directories in the res directory, and the corresponding layout file names remain unchanged, such as main.xml. layout-land is a horizontal screen layout, layout-port is a vertical screen layout, don't worry about the others, the simulator will automatically find them.

(2) In the above horizontal and vertical screen recognition, if the horizontal and vertical screens change, determine the direction in onCreate() or onConfigurationChanged(), and then re-setContentView in the corresponding method to load different layout xml layout files

Save and read data for horizontal and vertical screen switching

In addition, each screen switching in Android will restart the Activity, so the current activity status should be saved before the Activity is destroyed, and when the Activity is Created again Load the configuration so that the game in progress won't automatically restart!

Activity Data Saving

(1) If the Activity is Destroyed or Recreated when rotating the screen due to system resource constraints, the system will have this Activity when the user returns to it. For past records, the system will use those saved record data (instance state), which are some key-value pairs stored in the Bundle object. The system uses Bundle to save information by default

(2) In order to save additional updates To add more data to the instance state, we need to rewrite the callback function onSaveInstanceState(Bundle outState). The system will pass the Bundle object when the Activity is Destroyed by an exception, so that we can add additional information to the Bundle and save it to the system. If the system wants to re-create this Activity instance after the Activity is Destroyed, the previous Bundle object will (the system) be passed to your activity's

(3) When the Activity starts to stop, the system will call onSaveInstanceState(Bundle outState ), Activity can use a collection of key-value pairs to save state information. This method will save the status information of the Activity view by default, such as the text in the EditText component or the sliding position of the ListView

Activity data recovery

(1) When the Activity is rebuilt from Destory, we can Restore the saved state from the Activity's Bundle passed by the system. Both the onCreate() and onRestoreInstanceState() callback methods receive the same Bundle, which contains the same instance state information.

(2) Since the onCreate() method will be called both when a new Activity instance is created for the first time and when a previously Destoryed instance is re-created, we must check whether it is a Bundle object before trying to read it. null. If it is null, the system creates a new Activity instance instead of restoring the previously Destoryed Activity.

(3) You can also choose to implement onRestoreInstanceState() instead of restoring data in the onCreate method. The onRestoreInstanceState() method will be executed after the onStart() method. The system will only call onRestoreInstanceState() when there is state information that needs to be restored, so there is no need to check whether the Bundle is null.

The above is the knowledge about the life cycle of Android Activity horizontal and vertical screen switching introduced by the editor. I hope it will be helpful to everyone!

For more articles related to the life cycle of Android Activity horizontal and vertical screen switching, please pay attention to the PHP Chinese website!


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Why is Java a popular choice for developing cross-platform desktop applications?Why is Java a popular choice for developing cross-platform desktop applications?Apr 25, 2025 am 12:23 AM

Javaispopularforcross-platformdesktopapplicationsduetoits"WriteOnce,RunAnywhere"philosophy.1)ItusesbytecodethatrunsonanyJVM-equippedplatform.2)LibrarieslikeSwingandJavaFXhelpcreatenative-lookingUIs.3)Itsextensivestandardlibrarysupportscompr

Discuss situations where writing platform-specific code in Java might be necessary.Discuss situations where writing platform-specific code in Java might be necessary.Apr 25, 2025 am 12:22 AM

Reasons for writing platform-specific code in Java include access to specific operating system features, interacting with specific hardware, and optimizing performance. 1) Use JNA or JNI to access the Windows registry; 2) Interact with Linux-specific hardware drivers through JNI; 3) Use Metal to optimize gaming performance on macOS through JNI. Nevertheless, writing platform-specific code can affect the portability of the code, increase complexity, and potentially pose performance overhead and security risks.

What are the future trends in Java development that relate to platform independence?What are the future trends in Java development that relate to platform independence?Apr 25, 2025 am 12:12 AM

Java will further enhance platform independence through cloud-native applications, multi-platform deployment and cross-language interoperability. 1) Cloud native applications will use GraalVM and Quarkus to increase startup speed. 2) Java will be extended to embedded devices, mobile devices and quantum computers. 3) Through GraalVM, Java will seamlessly integrate with languages ​​such as Python and JavaScript to enhance cross-language interoperability.

How does the strong typing of Java contribute to platform independence?How does the strong typing of Java contribute to platform independence?Apr 25, 2025 am 12:11 AM

Java's strong typed system ensures platform independence through type safety, unified type conversion and polymorphism. 1) Type safety performs type checking at compile time to avoid runtime errors; 2) Unified type conversion rules are consistent across all platforms; 3) Polymorphism and interface mechanisms make the code behave consistently on different platforms.

Explain how Java Native Interface (JNI) can compromise platform independence.Explain how Java Native Interface (JNI) can compromise platform independence.Apr 25, 2025 am 12:07 AM

JNI will destroy Java's platform independence. 1) JNI requires local libraries for a specific platform, 2) local code needs to be compiled and linked on the target platform, 3) Different versions of the operating system or JVM may require different local library versions, 4) local code may introduce security vulnerabilities or cause program crashes.

Are there any emerging technologies that threaten or enhance Java's platform independence?Are there any emerging technologies that threaten or enhance Java's platform independence?Apr 24, 2025 am 12:11 AM

Emerging technologies pose both threats and enhancements to Java's platform independence. 1) Cloud computing and containerization technologies such as Docker enhance Java's platform independence, but need to be optimized to adapt to different cloud environments. 2) WebAssembly compiles Java code through GraalVM, extending its platform independence, but it needs to compete with other languages ​​for performance.

What are the different implementations of the JVM, and do they all provide the same level of platform independence?What are the different implementations of the JVM, and do they all provide the same level of platform independence?Apr 24, 2025 am 12:10 AM

Different JVM implementations can provide platform independence, but their performance is slightly different. 1. OracleHotSpot and OpenJDKJVM perform similarly in platform independence, but OpenJDK may require additional configuration. 2. IBMJ9JVM performs optimization on specific operating systems. 3. GraalVM supports multiple languages ​​and requires additional configuration. 4. AzulZingJVM requires specific platform adjustments.

How does platform independence reduce development costs and time?How does platform independence reduce development costs and time?Apr 24, 2025 am 12:08 AM

Platform independence reduces development costs and shortens development time by running the same set of code on multiple operating systems. Specifically, it is manifested as: 1. Reduce development time, only one set of code is required; 2. Reduce maintenance costs and unify the testing process; 3. Quick iteration and team collaboration to simplify the deployment process.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor