屏幕旋转

来源:互联网 发布:淘宝订单好评短链接 编辑:程序博客网 时间:2024/04/30 22:12

播放器支持手机上下翻转

楼主百度了好久,始终没有得到合理的方法,最后看到了同事写的瞬间豁然大开

 OrientationEventListener orient = null;
 orient = new OrientationEventListener(mContext) {


            @Override
            public void onOrientationChanged(int orientation) {
                //right land
                if (orientation >= 45 && orientation < 135) {
                    setPlayBarViewRotation(Surface.ROTATION_180);


                //left land
                } else if (orientation >= 225 && orientation < 315) {
                    setPlayBarViewRotation(Surface.ROTATION_0);
                }
            }
        };
        orient.enable();
    }


private void setPlayBarViewRotation(int rotation) {
        if (playBarView == null)
            return;
        if (rotation == Surface.ROTATION_0)
            playBarView.setRotation(0);
        else if (rotation == Surface.ROTATION_180)
            playBarView.setRotation(180);
    }

今天在此总结一些关于屏幕旋转的方法

1. AndroidManifest.xml设置

如果单单想设置横屏或者竖屏,那么只需要添加横竖屏代码:

android:screenOrientation="landscape"横屏设置;android:screenOrientation="portrait"竖屏设置;

这种方法的优点:即使屏幕旋转,Activity也不会重新onCreate。

缺点:屏幕只有一个方向。

2. 代码动态设置

如果你需要动态改变横竖屏设置,那么,只需要在代码中调用setRequestedOrientation()函数:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//横屏设置setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//竖屏设置setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);//默认设置

这种方法优点:可以随意动态设置,满足我们人为改变横竖屏的要求,同时满足横竖屏UI不同的设计需求;

缺点:如果改变设置,那么,Activity会被销毁,重新构建,即重新onCreate;

3. 重写onConfigurationChanged

如果你不希望旋转屏幕的时候Activity被不断的onCreate(这种情况往往会造成屏幕切换时的卡顿),那么,可以使用此方法:

首先,在AndroidMainfest.xml中添加configChanges:

<activity android:name=".Test" android:configChanges="orientation|keyboard"></activity>

注意,keyboardHidden表示键盘辅助功能隐藏,如果你的开发API等级等于或高于13,还需要设置screenSize,因为screenSize会在屏幕旋转时改变;

android:configChanges="keyboardHidden|orientation|screenSize"

然后,在Activity中重写onConfigurationChanged方法,这个方法将会在屏幕旋转变化时,进行监听处理:

public void onConfigurationChanged(Configuration newConfig) {// TODO Auto-generated method stubsuper.onConfigurationChanged(newConfig);if (newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE){// Nothing need to be done here } else { // Nothing need to be done here  } }

这个方法的优点:我们可以随时监听屏幕旋转变化,并对应做出相应的操作;
缺点:它只能一次旋转90度,如果一下子旋转180度,onConfigurationChanged函数不会被调用。


0 0