在不旋转应用程序的情况下捕获设备旋转

问题描述 投票:0回答:2

我有一个Android Webview应用程序,我的活动设置为portrait

<activity
        android:name=".activity.MainActivity"
        android:screenOrientation="portrait"
        android:windowSoftInputMode="stateUnspecified|adjustResize"></activity>

但我希望看到用户旋转设备并且应用程序屏幕继续纵向的事件,但我需要利用此事件制作动画,只能从webview中制作动画并旋转一个视频。有没有人有这种情况的解决方案?

android android-layout android-activity rotation screen-rotation
2个回答
1
投票

如果你想旋转你的活动你应该删除android:screenOrientation =“portrait”并添加android:configChanges =“orientation | keyboardHidden”

<activity
    android:name=".activity.MainActivity"
    android:configChanges="orientation|keyboardHidden"
    android:windowSoftInputMode="stateUnspecified|adjustResize"></activity>

然后覆盖活动中的onConfigurationChanged()方法,以便在旋转应用程序时获得回调

class MainActivity extends AppCompatActivity {
    ...

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

        // Checks the orientation of the screen
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            // App is rotated to landscape
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
            // App is rotated to portrait
        }
    }
}

在这种情况下,不会重新创建活动,您应该自己处理更新UI组件。看看original documentation获取更多细节;)

更新:

如果要在纵向模式下保持活动并仅检测旋转,请查看:


0
投票

解决:

    SensorManager sensorManager = (SensorManager) this.getSystemService(Context.SENSOR_SERVICE);
    sensorManager.registerListener(new SensorEventListener()
    {
        int orientation = -1;

        @Override
        public void onSensorChanged(SensorEvent event)
        {
            if (event.values[1] < 6.5 && event.values[1] > -6.5)
            {
                if (orientation != 1)
                {
                    Log.d("SensorLog", "Landscape");
                }
                orientation = 1;
            }
            else
            {
                if (orientation != 0)
                {
                    Log.d("SensorLog", "Portrait");
                }
                orientation = 0;
            }
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy)
        {
            // TODO Auto-generated method stub

        }
    }, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_GAME);
© www.soinside.com 2019 - 2024. All rights reserved.