现在的位置: 首页 > 综合 > 正文

android横竖屏切换的一点感想

2013年09月11日 ⁄ 综合 ⁄ 共 1792字 ⁄ 字号 评论关闭

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

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

    	<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"

这两个属性。

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

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)就行了

  @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        this.setRequestedOrientation(mOrientation);
    }

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

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

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

    @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();
    }

抱歉!评论已关闭.