操作方向变化时出现的问题 [英] Problems when handling orientation changes
问题描述
我需要处理在我的Android应用程序的方向变化。为此,我决定使用 OrientationEventListener
便利类。但他的回调方法给出有些奇怪的行为。
I need to handle orientation changes in my Android application. For this purpose I decided to use OrientationEventListener
convenience class. But his callback method is given somewhat strange behavior.
我的应用程序开始在人像模式,然后最终切换到lanscape之一。我有一些自定义的code回调 onOrientationChanged
方法执行,提供了一些额外的UI处理逻辑 - 它有 findViewById 打了几个电话code>。
奇怪的是,从横向切换时返回到肖像模式 onOrientationChanged
回调被调用两次,更糟的是 - 第二个呼叫正在处理的坏 上下文
- findViewById
方法开始返回空
。这些调用直接从取得的 MainThread 的
My application starts in the portrait mode and then eventually switches to the lanscape one. I have some custom code executing in the callback onOrientationChanged
method that provides some additional UI handling logic - it has a few calls to findViewById
.
What is strange is that when switching back from landscape to portrait mode onOrientationChanged
callback is called twice, and what's even worse - the second call is dealing with bad Context
- findViewById
method starts returning null
. These calls are made right from the MainThread
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listener = new OrientationListener();
}
@Override
protected void onResume() {
super.onResume();
// enabling listening
listener.enable();
}
@Override
protected void onPause() {
super.onPause();
// disabling listening
listener.disable();
}
我复制与虚拟活动
相同的行为,而不只是一个带有定向hadling涉及任何逻辑。
我由pressing启动从Android 2.2的模拟器方向开关的按Ctrl + F11 的
可能是什么问题?
I've replicated the same behavior with a dummy Activity
without any logic except for one that deals with orientation hadling.
I initiate orientation switch from the Android 2.2 emulator by pressing Ctrl+F11
What could be wrong?
UPD:
内部类实现 OrientationEventListener
private class OrientationListener extends OrientationEventListener {
public OrientationL() {
super(getBaseContext());
}
@Override
public void onOrientationChanged(int orientation) {
toString();
}
}
}
推荐答案
这是在模拟器中唯一一个文档的错误。一个真正的设备将不会出现此双生命周期事件的行为。我前一阵子有同样的问题,并消失在真实设备上。
This is a documented bug in the emulator ONLY. A real device will not exhibit this double-lifecycle-events behavior. I had the same issue a while ago and it disappears on a real device.
我建议你通过测试只在一个方向取向的变化,直到你把你的手在物理上的电话,如果你能忽略的问题。否则,你可能能够通过保持一个静态布尔表示身边你已经通过第一套去跳过第二套生命周期的呼叫。
I would suggest ignoring the problem if you can by only testing orientation changes in one direction until you get your hands on a physical phone. Otherwise you might be able to "skip" the second set of lifecycle calls by keeping a static boolean around indicating you've already gone through the first set.
请参阅这个问题报告获取更多信息。
这篇关于操作方向变化时出现的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!