Problems when handling orientation changes

放肆的年华 提交于 2019-11-28 04:21:38

问题


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.

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();
}

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: Inner class that implements OrientationEventListener

private class OrientationListener extends OrientationEventListener {
    public OrientationL() {
        super(getBaseContext());
    }

    @Override
    public void onOrientationChanged(int orientation) {

        toString();

    }
}

}


回答1:


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.

See this issue report for more info.




回答2:


Have you tried using onConfigurationChanged?

@Override
public void onConfigurationChanged(Configuration newConfig) {
 if(newConfig.equals(Configuration.ORIENTATION_LANDSCAPE)…



回答3:


Add android:configChanges="orientation" in manifest file in activity tag like

<activity android:label="@string/app_name" android:configChanges="orientation" android:name=".com.androidpeople">



来源:https://stackoverflow.com/questions/2988072/problems-when-handling-orientation-changes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!