android橫豎屏切換的一點感想

來源:互聯網
上載者:User

  最近用到橫豎屏切換的相關知識,大家也都知道橫豎屏切換後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 /> } 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.