在我的Android应用程序中,当我旋转设备(滑出键盘)时,我的Activity
会重新启动(称为onCreate
).现在,这可能是应该的,但我在onCreate
方法中做了很多初始设置,所以我需要:
- 将所有初始设置放在另一个功能中,这样就不会在设备旋转或
- 使
onCreate
不再被调用,布局只是调整或调整 - 将应用程序限制为仅纵向,以便不调用
onCreate
.
在我的Android应用程序中,当我旋转设备(滑出键盘)时,我的Activity
会重新启动(称为onCreate
).现在,这可能是应该的,但我在onCreate
方法中做了很多初始设置,所以我需要:
onCreate
不再被调用,布局只是调整或调整onCreate
.Using the Application Class个
根据您在初始化过程中所做的操作,可以考虑创建一个扩展Application
的新类,并将初始化代码移动到该类中的重写onCreate
方法.
public class MyApplicationClass extends Application {
@Override
public void onCreate() {
super.onCreate();
// TODO Put your application initialization code here.
}
}
application类中的onCreate
仅在创建整个应用程序时调用,因此活动会在方向或键盘可见性更改时重新启动,不会触发它.
最好将该类的实例公开为单例,并使用getter和setter公开您正在初始化的应用程序变量.
NOTE: You'll need to specify the name of your new Application class in the manifest for it to be registered and used:个
<application
android:name="com.you.yourapp.MyApplicationClass"
Reacting to Configuration Changes [UPDATE: this is deprecated since API 13; 100]
作为另一种 Select ,您可以让应用程序监听可能导致重新启动的事件(如方向和键盘可见性更改),并在活动中处理它们.
首先,将android:configChanges
node 添加到活动的 list node
<activity android:name=".MyActivity"
android:configChanges="orientation|keyboardHidden"
android:label="@string/app_name">
或Android 3.2 (API level 13) and newer:
<activity android:name=".MyActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:label="@string/app_name">
然后在活动中覆盖onConfigurationChanged
方法并调用setContentView
,以强制GUI布局在新方向上重新完成.
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setContentView(R.layout.myLayout);
}