在我的Android应用程序中,当我旋转设备(滑出键盘)时,“活动”将重新启动(调用onCreate)。现在,这可能是应该的,但我在onCreate方法中做了很多初始设置,所以我需要:
将所有初始设置放在另一个功能中,这样不会在设备旋转或使其不再调用Create,布局仅调整或将应用程序限制为仅肖像,以便不调用onCreate。
在我的Android应用程序中,当我旋转设备(滑出键盘)时,“活动”将重新启动(调用onCreate)。现在,这可能是应该的,但我在onCreate方法中做了很多初始设置,所以我需要:
将所有初始设置放在另一个功能中,这样不会在设备旋转或使其不再调用Create,布局仅调整或将应用程序限制为仅肖像,以便不调用onCreate。
当前回答
您可以使用此代码锁定屏幕的当前方向。。。
int currentOrientation =context.getResources().getConfiguration().orientation;
if (currentOrientation == Configuration.ORIENTATION_PORTRAIT) {
((Activity) context).setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else {
((Activity) context). setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
其他回答
我所做的。。。
在清单的活动部分中,添加了:
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台设备……没有。(不知道为什么会有什么不同。)
您所描述的是默认行为。您必须通过添加以下内容自行检测和处理这些事件:
android:configChanges
然后是您想要处理的更改。因此,对于方向,您可以使用:
android:configChanges="orientation"
对于正在打开或关闭的键盘,您可以使用:
android:configChanges="keyboardHidden"
如果要同时处理这两种情况,只需使用pipe命令将它们分开,如:
android:configChanges="keyboardHidden|orientation"
这将在您调用的任何Activity中触发onConfigurationChanged方法。如果重写该方法,则可以传入新值。
希望这有帮助。
我刚刚发现了这个传说:
为了通过方向更改保持活动活动,并通过onConfigurationChanged处理活动,上面的文档和代码示例在Manifest文件中建议:
<activity android:name=".MyActivity"
android:configChanges="orientation|keyboardHidden"
android:label="@string/app_name">
这有一个额外的好处,那就是它总是有效的。
另一个好处是,省略keyboardHidden可能看起来合乎逻辑,但它会导致模拟器失败(至少对于Android 2.1):只指定方向会使模拟器有时同时调用OnCreate和onConfigurationChanged,而其他时候只调用OnCreate。
我还没有看到设备出现故障,但我听说过其他设备的仿真器出现故障。因此值得记录。
注意:如果将来有人和我面临同样的问题,我会发布这个答案。对我来说,下面这行是不够的:
android:configChanges="orientation"
当我旋转屏幕时,没有调用方法`onConfigurationChanged(配置新配置)。
解决方案:即使问题与方向有关,我也必须添加“screenSize”。因此,在AndroidManifest.xml文件中,添加以下内容:
android:configChanges="keyboardHidden|orientation|screenSize"
然后实现方法onConfigurationChanged(Configuration newConfig)