Android 横竖屏切换

Android 判断当前屏幕是横屏还是竖屏
//获取设置的配置信息

Configuration mConfiguration = this.getResources().getConfiguration(); 
//获取屏幕方向
int ori = mConfiguration.orientation; 
if (ori == mConfiguration.ORIENTATION_LANDSCAPE) {
    //当前为横屏
    //强制为竖屏
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else if (ori == mConfiguration.ORIENTATION_PORTRAIT) {
    //当前为竖屏
    //强制为横屏
   setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}

这个时候回调用onConfigurationChanged 这个方法
需要添加或者清除Flage
Android 横竖屏切换_第1张图片

@Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            //横屏
            //强制为竖屏
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        } else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            //竖屏
            // 强制为横屏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }
    }

最后看一下点击横屏的点击事件
Android 横竖屏切换_第2张图片

 if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
                    //横屏
                    //强制为竖屏
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                            ViewGroup.LayoutParams.MATCH_PARENT, (int) dp2px(210));
                    txVideoview.setLayoutParams(lp);
                } else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
                    //竖屏
                    //强制为横屏
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                            ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                    txVideoview.setLayoutParams(lp);
                }

最后需要在Activity中加上属性

android:configChanges="orientation|screenSize"

防止手机旋转时, Activity被重建.

你可能感兴趣的:(Android)