您的位置:首页 > 移动开发 > Android开发

Android屏幕旋转使用

2018-01-03 13:57 393 查看
查看了很多有关手机旋转的案里,于是就总结了一下

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android