最近用到橫豎屏切換的相關知識,大家也都知道橫豎屏切換後Activity會重新執行onCreat函數。但是只要在Android工程的Mainfest.xml中
加入android:screenOrientation="user" android:configChanges="orientation|keyboardHidden"之後 <activity android:name=".MainActivity" android:label="@string/app_name"<br />android:screenOrientation="user" android:configChanges="orientation|keyboardHidden"><br /><intent-filter><br /><action android:name="android.intent.action.MAIN" /><br /><category android:name="android.intent.category.LAUNCHER" /><br /></intent-filter><br /></activity>
橫豎屏切換之後就不會去執行OnCreat函數了,而是會去調用onConfigurationChanged()這樣我們就能控制橫豎屏的切換了。
當然你只想讓它一直是橫屏表示的話,只要設定android:screenOrientation="landscape"就行了。
但是如果我想讓它啟動的時候是什麼橫屏的話就橫屏表示,縱屏的話就縱屏表示,然後手機切換橫豎屏就不能用了該怎麼解決呢?
首先: 在Mainfest.xml中追加android:screenOrientation="sensor" android:configChanges="orientation|keyboardHidden"
這兩個屬性。
第二步:取得螢幕的長和寬,進行比較設定橫豎屏的變數。
Display display = getWindowManager().getDefaultDisplay();<br /> int width = display.getWidth();<br /> int height = display.getHeight();<br /> if (width > height) {<br /> orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;<br /> } else {<br /> orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;<br /> }
第三步:在onConfigurationChanged()函數中追加this.setRequestedOrientation(mOrientation)就行了
@Override<br /> public void onConfigurationChanged(Configuration newConfig) {<br /> super.onConfigurationChanged(newConfig);<br /> this.setRequestedOrientation(mOrientation);<br /> }
但是這樣的話你切到別的畫面的時候再回到原畫面,它就仍然是橫的或者是縱的。怎麼讓它從別的螢幕回來後,又重新橫豎屏布局呢?
只要在OnResume()中在設定下就行了。但是這個只支援橫豎屏只有一個layout的。橫豎屏分別對應layout的還不知道該怎麼解決。
大家有什麼想法的話可以留言。
@Override<br /> protected void onResume() {<br /> mOrientation = ActivityInfo.SCREEN_ORIENTATION_USER;<br /> this.setRequestedOrientation(mOrientation);<br /> Display display = getWindowManager().getDefaultDisplay();<br /> int width = display.getWidth();<br /> int height = display.getHeight();<br /> if (width > height) {<br /> mOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;<br /> } else {<br /> mOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;<br /> }</p><p> super.onResume();<br /> }