在我的 Android 应用程序中,当我旋转设备(滑出键盘)时,我的 Activity
会重新启动(调用 onCreate
).现在,这可能就是它应该的样子,但是我在 onCreate
方法中做了很多初始设置,所以我需要:
In my Android application, when I rotate the device (slide out the keyboard) then my Activity
is restarted (onCreate
is called). Now, this is probably how it's supposed to be, but I do a lot of initial setting up in the onCreate
method, so I need either:
onCreate
不再被调用,布局只是调整或onCreate
.onCreate
is not called again and the layout just adjusts oronCreate
is not called.使用应用程序类
根据您在初始化中所做的事情,您可以考虑创建一个扩展 Application
的新类,并将您的初始化代码移动到该类中重写的 onCreate
方法中.
Depending on what you're doing in your initialization you could consider creating a new class that extends Application
and moving your initialization code into an overridden onCreate
method within that class.
public class MyApplicationClass extends Application {
@Override
public void onCreate() {
super.onCreate();
// TODO Put your application initialization code here.
}
}
应用程序类中的onCreate
仅在整个应用程序创建时被调用,因此Activity在方向重启或键盘可见性变化时不会触发它.
The onCreate
in the application class is only called when the entire application is created, so the Activity restarts on orientation or keyboard visibility changes won't trigger it.
最好将此类的实例公开为单例,并使用 getter 和 setter 公开您正在初始化的应用程序变量.
It's good practice to expose the instance of this class as a singleton and exposing the application variables you're initializing using getters and setters.
注意:您需要在清单中指定新应用程序类的名称才能注册和使用它:
<application
android:name="com.you.yourapp.MyApplicationClass"
对配置更改做出反应 [更新:自 API 13 起已弃用;查看推荐的替代方案]
作为另一种选择,您可以让应用程序侦听可能导致重启的事件(例如方向和键盘可见性更改)并在您的 Activity 中处理它们.
As a further alternative, you can have your application listen for events that would cause a restart – like orientation and keyboard visibility changes – and handle them within your Activity.
首先将 android:configChanges
节点添加到 Activity 的清单节点
Start by adding the android:configChanges
node to your Activity's manifest node
<activity android:name=".MyActivity"
android:configChanges="orientation|keyboardHidden"
android:label="@string/app_name">
或对于 Android 3.2(API 级别 13)及更高版本:
<activity android:name=".MyActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:label="@string/app_name">
然后在 Activity 中重写 onConfigurationChanged
方法并调用 setContentView
以强制在新方向上重新完成 GUI 布局.
Then within the Activity override the onConfigurationChanged
method and call setContentView
to force the GUI layout to be re-done in the new orientation.
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setContentView(R.layout.myLayout);
}
这篇关于旋转Android上的活动重启的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!