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

android横竖屏切换的一点感想

2013-07-01 11:22 309 查看
/article/1853429.html

最近用到横竖屏切换的相关知识,大家也都知道横竖屏切换后Activity会重新执行onCreat函数。但是只要在Android工程的Mainfest.xml中

加入android:screenOrientation="user" android:configChanges="orientation|keyboardHidden"之后

[xhtml] view
plaincopy

<activity android:name=".MainActivity" android:label="@string/app_name"

android:screenOrientation="user" android:configChanges="orientation|keyboardHidden">

<intent-filter>

<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />

</intent-filter>

</activity>

横竖屏切换之后就不会去执行OnCreat函数了,而是会去调用onConfigurationChanged()这样我们就能控制横竖屏的切换了。

当然你只想让它一直是横屏表示的话,只要设置android:screenOrientation="landscape"就行了。

但是如果我想让它启动的时候是什么横屏的话就横屏表示,纵屏的话就纵屏表示,然后手机切换横竖屏就不能用了该怎么解决呢?

首先: 在Mainfest.xml中追加android:screenOrientation="sensor" android:configChanges="orientation|keyboardHidden"

这两个属性。

第二步:取得屏幕的长和宽,进行比较设置横竖屏的变量。

[java] view
plaincopy

Display display = getWindowManager().getDefaultDisplay();

int width = display.getWidth();

int height = display.getHeight();

if (width > height) {

orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;

} else {

orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;

}

第三步:在onConfigurationChanged()函数中追加this.setRequestedOrientation(mOrientation)就行了

[java] view
plaincopy

@Override

public void onConfigurationChanged(Configuration newConfig) {

super.onConfigurationChanged(newConfig);

this.setRequestedOrientation(mOrientation);

}

但是这样的话你切到别的画面的时候再回到原画面,它就仍然是横的或者是纵的。怎么让它从别的屏幕回来后,又重新横竖屏布局呢?

只要在OnResume()中在设定下就行了。但是这个只支持横竖屏只有一个layout的。横竖屏分别对应layout的还不知道该怎么解决。

大家有什么想法的话可以留言。

[java] view
plaincopy

@Override

protected void onResume() {

mOrientation = ActivityInfo.SCREEN_ORIENTATION_USER;

this.setRequestedOrientation(mOrientation);

Display display = getWindowManager().getDefaultDisplay();

int width = display.getWidth();

int height = display.getHeight();

if (width > height) {

mOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;

} else {

mOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;

}

super.onResume();

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