OnConfigurationChanged for Android

Source: Internet
Author: User

In Android development, if some events are triggered (such as screen spin events), the Activity will re-call the onCreate method to re-initialize the Activity, which is not only inefficient, but also causes data loss, the solution is to override the onConfigurationChanged method, and in AndroidManifest. declare configChanges for the Activity IN xml, so that the onConfigurationChanged method is called when a specific event is triggered, rather than the onCreate Method for reinitialization.


Generally, the following code is added to specify Activity in AndroidManifest. xml:

android:configChanges="orientation|keyboard|keyboardHidden"
This Code indicates that the onConfigurationChanged method of Activity is called when the device rotates, displays the keyboard, and hides the keyboard. If this statement is not declared, the onCreate method is called when a specific event is triggered.


The following is a Demo. We use data to simulate data changes when testing the screen rotation.

public class MainActivity extends Activity {private static final String TAG = "TEST";private int data;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Log.i(TAG, "onCreate");}@Overrideprotected void onStart() {// TODO Auto-generated method stubsuper.onStart();data = (int) (Math.random() * 100);Log.i(TAG, "onStart : " + data);}@Overridepublic void onConfigurationChanged(Configuration newConfig) {// TODO Auto-generated method stubsuper.onConfigurationChanged(newConfig);Log.i(TAG, "onConfigurationChanged : " + data);}}


Three screen effects:


The data is retained because the onCreate method is not enabled for three screens.

In addition, note that: super. onConfigurationChanged (newConfig) in the onConfigurationChanged () method must not be omitted. Otherwise, an android. app. SuperNotCalledException exception will be thrown.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.