安卓设置横竖屏的笔记

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34709057/article/details/81233555

首先在AndroidManifest.xml设置了

android:configChanges="orientation|keyboardHidden|screenSize"使其设换横竖屏是不会重新走生命周期。

使用代码

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);//设置90度方向的横屏
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//设置正方向的竖屏

一般这样设置的横竖屏是只有一个方向的,无论你怎么转屏幕,这个屏幕内容也不会跟着旋转的。(个人理解)

但我需要的是根据重力感应改变横屏的方向的,所以:得做一个监听

在oncreate中加入

orientationEventListener=new OrientationEventListener(this) {
    @Override
    public void onOrientationChanged(int orientation) {
        int value = getResources().getConfiguration().orientation;
      
        if (value == Configuration.ORIENTATION_LANDSCAPE){
            if (orientation > 45 && orientation < 135) {
               setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
            }else if (orientation > 225 && orientation < 315) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            }
        }
    }
};
orientationEventListener.enable();

在生命周期结束时使用

orientationEventListener.disable();

以下可能有用的资料:

int screenchange = Settings.System.getInt(context.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION);
重力感应:1表示已开启 0表示未开启

与上面的监听那里有联系:

if (orientation > 45 && orientation < 135) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
//                Log.d(MainActivity.TAG, "横屏翻转: ");
            } else if (orientation > 135 && orientation < 225) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
//                Log.d(MainActivity.TAG, "竖屏翻转: ");
            } else if (orientation > 225 && orientation < 315) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
//                Log.d(MainActivity.TAG, "横屏: ");
            } else if ((orientation > 315 && orientation < 360) || (orientation > 0 && orientation < 45)) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//                Log.d(MainActivity.TAG, "竖屏: ");
            }

猜你喜欢

转载自blog.csdn.net/qq_34709057/article/details/81233555