Android屏幕旋转使用

查看了很多有关手机旋转的案里,于是就总结了一下
1.首先是xml布局适配;
在自己的资源下创建layout-land和layout-port横竖屏布局,activity_main.xml的布局文件名要一样,如在layout文件夹也有同一个activity_main.xml布局文件,则它们的执行顺序是先从land/port文件夹索引,如果没有创建默认走layout文件夹下的xml,land和port文件下的布局必须同时存在,一旦两个文件夹中只有一个文件没有则会运行时报错;

下面我们来看其他的使用方法;
2.通过onConfigurationChanged()方法,在屏幕旋转时动态加载,不过这种只能获取横屏和竖屏,缺不能对当前旋转的角度进行判断;

@Override
    protected void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
      Configuration mConfiguration = this.getResources().getConfiguration();
        int ori = mConfiguration.orientation;
        if (ori == mConfiguration.ORIENTATION_LANDSCAPE) {
            //Horizontal screen
            horizontalScreen();
        } else if (ori == mConfiguration.ORIENTATION_PORTRAIT) {
            //Vertical screen
            VerticalScreen();
        }
    }

3.通过dispatchTouchEvent事件,获取当前window窗口的屏幕旋转角度;

     @Override
     public boolean dispatchTouchEvent(MotionEvent ev) {
            if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            int orientation = getScreenOrientation();
            if(orientation==0){
            //竖屏处理逻辑
           }else{
            //横屏处理逻辑
            }
        }
    }
}
    mWindowManager = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
     int rotation = mWindowManager.getDefaultDisplay().getRotation();
        //0表示是竖屏; 90表示是左横屏; 180表示是反向竖屏; 270表示是右横屏
        if (rotation == Surface.ROTATION_0) {
            return 0;
        } else if (rotation == Surface.ROTATION_90) {
            return 90;
        } else if (rotation == Surface.ROTATION_180) {
            return 180;
        } else if (rotation == Surface.ROTATION_270) {
            return 270;
        }
        return 0;
    }

4.还有一种是通过OrientationEventListener来实现,网上有很多实现,这里就不写了;
OrientationEventListener可参考:http://blog.csdn.net/xiao_yuanjl/article/details/78960632

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值