方向更改时,活动会继续重新启动(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.

最满意答案

您可以通过在manifest.xml中的activity元素中声明特定属性来完成此操作。 有问题的元素叫做android:configChanges ,你需要注册orientation的字符串值。

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

从文档 :

现在,当其中一个配置发生更改时,MyActivity不会重新启动。 相反,Activity会收到对onConfigurationChanged()的调用。 此方法传递一个Configuration对象,该对象指定新的设备配置。 通过阅读配置中的字段,您可以确定新的配置并通过更新界面中使用的资源进行适当的更改。 在调用此方法时,您的Activity的Resources对象将更新为基于新配置返回资源,因此您可以轻松地重置UI的元素,而无需系统重新启动您的Activity

因此,这样做会导致您的Activity无法重新启动,并且还会回调onConfigurationChanged()以便可以自己处理更改。

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.

更多推荐

Is,滑动,键盘,防止,电脑培训,计算机培训,IT培训"/> <meta name="description"