How to detect when the device switch from portrait to landscape mode? [duplicate]

空扰寡人 提交于 2019-11-27 21:41:09

See the official documentation http://developer.android.com/guide/topics/resources/runtime-changes.html

Changing it will actually create a new view and onCreate will be called again.

Furthermore you can check it via

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
        Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
    }
}

You can check the onSavedInstanceState from your onCreate method, if it is not null means this is configuration change.

Another approach is using OrientationEventListener.

It can be used like this:

 OrientationEventListener mOrientationEventListener = new OrientationEventListener(
            this, SensorManager.SENSOR_DELAY_NORMAL) {

        @Override
        public void onOrientationChanged(int orientation) {
            //checking if device was rotated
            if (orientationPortrait != isPortrait(orientation)) {
                orientationPortrait = !orientationPortrait;
                Log.d(TAG, "Device was rotated!");
            }
        }
    };

To check orientation:

private boolean isPortrait(int orientation) {
    return (orientation >= (360 - 90) && orientation <= 360) || (orientation >= 0 && orientation <= 90);
}

And don't forget to enable and disable listener:

if (mOrientationEventListener != null) {
        mOrientationEventListener.enable();
    }

if (mOrientationEventListener != null) {
        mOrientationEventListener.disable();
    }

Usually Orientation change calls OnCreate() unless you have done something to make it do otherwise.

You can put the logic there.

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