捕获方向改变事件发生之前(Capture orientation change event befo

2019-08-17 07:03发布

这是简单的锁定方向为纵向或横向。

<activity android:name=".MyActivity"
           android:screenOrientation="portrait">

或捕捉当屏幕旋转:

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}

但我怎么能抓住一个旋转的事件,它发生过吗? 我想控制我的布局会发生什么,如果方向改变,重写的实际旋转屏幕的默认行为。 可能吗?

Answer 1:

使用此片的代码的onPause()方法。 当rotatio变化,activty重新coustructs它的自我,这意味着上创建的又一次打来电话,之前的活动是结束();

    int currentOrientation = getResources().getConfiguration().orientation;
    if (currentOrientation == Configuration.ORIENTATION_LANDSCAPE){
        if (display.getRotation() == Surface.ROTATION_0)
        // play with different angles e.g ROTATION_90, ROTATION_180
    }

因此,当旋转改变以前activites的的onPause()将被调用,在这个阶段,你可以决定你要使用新的方向是什么。



Answer 2:

  1. 强制通过活动停留在一个模式(例如,横向) setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);onCreate(..)

  2. 附上自己的定位监听器,

    orientationEventListener =新OrientationEventListener(此,SensorManager.SENSOR_DELAY_UI){

      @Override public void onOrientationChanged(int orientation) { if (Math.abs(orientation - 90) < 30){ // your device orientation has changed, you can update UI accordingly, (layout won't rotate). } }; orientationEventListener.enable(); 

请记住,如果你这样做,您将收到的X,Y轴的触摸事件“倒”,当你放弃配置更改。 另外,如果你有一个导航栏,它会保持它在哪里,不会旋转,以及!



文章来源: Capture orientation change event before it happens