在介绍之前,我们需要先了解默认情况下android屏幕旋转的机制:
默认情况下,当用户手机的重力感应器打开后,旋转屏幕方向,会导致当前activity发生onDestroy-> onCreate,这样会重新构造当前activity和界面布局,如果在Camera界面,则表现为卡顿或者黑屏一段时间。如果是在横竖屏UI设计方面,那么想很好地支持屏幕旋转,则建议在res中建立layout-land和layout-port两个文件夹,把横屏和竖屏的布局文件分别放入对应的layout文件夹中。
了解了这些以后,我们对android的屏幕旋转方法进行如下总结:
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>
android:configChanges="keyboardHidden|orientation|screenSize"
然后,在Activity中重写onConfigurationChanged方法,这个方法将会在屏幕旋转变化时,进行监听处理:
<pre class="java" name="code">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
}
}
private OrientationEventListener mOrientationListener; // screen orientation listener
private boolean mScreenProtrait = true;
private boolean mCurrentOrient = false;
abstract protected void OrientationChanged(int orientation);//screen orientation change event
private final void startOrientationChangeListener() {
mOrientationListener = new OrientationEventListener(this) {
@Override
public void onOrientationChanged(int rotation) {
if (((rotation >= 0) && (rotation <= 45)) || (rotation >= 315)||((rotation>=135)&&(rotation<=225))) {//portrait
mCurrentOrient = true;
if(mCurrentOrient!=mScreenProtrait)
{
mScreenProtrait = mCurrentOrient;
OrientationChanged(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Log.d(TAG, "Screen orientation changed from Landscape to Portrait!");
}
}
else if (((rotation > 45) && (rotation < 135))||((rotation>225)&&(rotation<315))) {//landscape
mCurrentOrient = false;
if(mCurrentOrient!=mScreenProtrait)
{
mScreenProtrait = mCurrentOrient;
OrientationChanged(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
Log.d(TAG, "Screen orientation changed from Portrait to Landscape!");
}
}
}
};
mOrientationListener.enable();
}
startOrientationChangeListener();