Activity keeps restarting when orientation changes

被刻印的时光 ゝ 提交于 2020-01-13 05:16:50

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/7129404/activity-keeps-restarting-when-orientation-changes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!