在我的Android应用程序中,当我旋转设备(滑出键盘)时,“活动”将重新启动(调用onCreate)。现在,这可能是应该的,但我在onCreate方法中做了很多初始设置,所以我需要:
将所有初始设置放在另一个功能中,这样不会在设备旋转或使其不再调用Create,布局仅调整或将应用程序限制为仅肖像,以便不调用onCreate。
在我的Android应用程序中,当我旋转设备(滑出键盘)时,“活动”将重新启动(调用onCreate)。现在,这可能是应该的,但我在onCreate方法中做了很多初始设置,所以我需要:
将所有初始设置放在另一个功能中,这样不会在设备旋转或使其不再调用Create,布局仅调整或将应用程序限制为仅肖像,以便不调用onCreate。
当前回答
Android 3.2及更高版本更新:
警告:从Android 3.2(API级别13)开始,当设备在纵向和横向方向之间切换时,“屏幕大小”也会发生变化。因此,如果在为API级别13或更高级别开发时(如minSdkVersion和targetSdkVersion属性所声明的),想要防止因方向改变而导致运行时重新启动,则除了“方向”值之外,还必须包含“screenSize”值。也就是说,您必须声明android:configChanges=“orientation|screenSize”。但是,如果您的应用程序以API级别12或更低为目标,则您的活动始终自行处理此配置更改(即使在Android 3.2或更高版本的设备上运行时,此配置更改也不会重新启动您的活动)。
从…起http://web.archive.org/web/20120805085007/http://developer.android.com/guide/topics/resources/runtime-更改.html
其他回答
与其试图阻止onCreate()被完全激发,不如尝试检查传递到事件中的Bundle savedInstanceState,看看它是否为null。
例如,如果我有一些逻辑应该在真正创建“活动”时运行,而不是在每次方向更改时运行,那么只有当savedInstanceState为空时,我才在onCreate()中运行该逻辑。
否则,我仍然希望布局按照方向正确重新绘制。
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_list);
if(savedInstanceState == null){
setupCloudMessaging();
}
}
不确定这是否是最终答案,但这对我来说是有效的。
我发现这样做的方法是使用onRestoreInstanceState和onSaveInstanceState事件在Bundle中保存一些东西(即使您不需要保存任何变量,也只需在其中放置一些东西,这样Bundle就不会为空)。然后,在onCreate方法上,检查Bundle是否为空,如果为空,则进行初始化,如果不是,则执行初始化。
Android 3.2及更高版本更新:
警告:从Android 3.2(API级别13)开始,当设备在纵向和横向方向之间切换时,“屏幕大小”也会发生变化。因此,如果在为API级别13或更高级别开发时(如minSdkVersion和targetSdkVersion属性所声明的),想要防止因方向改变而导致运行时重新启动,则除了“方向”值之外,还必须包含“screenSize”值。也就是说,您必须声明android:configChanges=“orientation|screenSize”。但是,如果您的应用程序以API级别12或更低为目标,则您的活动始终自行处理此配置更改(即使在Android 3.2或更高版本的设备上运行时,此配置更改也不会重新启动您的活动)。
从…起http://web.archive.org/web/20120805085007/http://developer.android.com/guide/topics/resources/runtime-更改.html
我所做的。。。
在清单的活动部分中,添加了:
android:configChanges="keyboardHidden|orientation"
在活动代码中,实现:
//used in onCreate() and onConfigurationChanged() to set up the UI elements
public void InitializeUI()
{
//get views from ID's
this.textViewHeaderMainMessage = (TextView) this.findViewById(R.id.TextViewHeaderMainMessage);
//etc... hook up click listeners, whatever you need from the Views
}
//Called when the activity is first created.
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
InitializeUI();
}
//this is called when the screen rotates.
// (onCreate is no longer called when screen rotates due to manifest, see: android:configChanges)
@Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
setContentView(R.layout.main);
InitializeUI();
}
onConfigurationChanged is called when the screen rotates.
(onCreate is no longer called when the screen rotates due to manifest, see:
android:configChanges)
清单的哪个部分告诉它“不要调用onCreate()”?
而且谷歌的文档说要避免使用android:configChanges(除非作为最后手段)。但是,他们建议的替代方法都使用android:configChanges。
根据我的经验,模拟器总是在旋转时调用onCreate()。但我运行相同代码的1-2台设备……没有。(不知道为什么会有什么不同。)