简体   繁体   中英

Activity keeps restarting when orientation changes

how do you keep the activity from restarting when the screen rotates or when then user slides the keyboard on the phone? Is this possible? Is there a work around or something? All relevant answers are appreciated.

You can do this by declaring a specific attribute in your activity element in your manifest.xml . The element in question is called android:configChanges , and you need to register the string value of orientation .

<activity android:name=".MyActivity"
      android:configChanges="orientation"
      android:label="@string/app_name">

From the documentation :

Now when one of these configurations change, MyActivity is not restarted. Instead, the Activity receives a call to onConfigurationChanged(). This method is passed a Configuration object that specifies the new device configuration. By reading fields in the Configuration, you can determine the new configuration and make appropriate changes by updating the resources used in your interface. At the time this method is called, your Activity's Resources object is updated to return resources based on the new configuration, so you can easily reset elements of your UI without the system restarting your Activity

So doing this will cause your Activity to not restart, and will also callback to onConfigurationChanged() so that you can handle the change yourself.

If you read the documentation here , you will see that you can specify the following in your manifest:

<activity ...
    android:configChanges="orientation">

Once you have this you can implement the onConfigurationChanged() method to receive notifications about orientation change, or just use the base class's implementation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM