Android橫豎屏總結)

來源:互聯網
上載者:User

橫豎屏切換後Activity會重新執行onCreat函數,但是在Android工程的Mainfest.xml中加入android:screenOrientation="user" android:configChanges="orientation|keyboardHidden"之後,橫豎屏切換之後就不會去執行OnCreat函數了,而是會去調用onConfigurationChanged(),這樣我們就能控制橫豎屏的切換了。
或者在res目錄下建立layout-land和layout-port目錄,相應的layout檔案不變。layout-land是橫屏的layout,layout-port是豎屏的layout。

 

如果想讓它一直是橫屏顯示的話,只要在設定檔中設定android:screenOrientation="landscape"就行了,或者在代碼中 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);。如果想讓它一直是豎屏顯示的話,只要在設定檔中設定android:screenOrientation="portrait"就行了,或者在代碼中setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);。

 

啟動的時候是橫屏的話就橫屏表示,縱屏的話就縱屏表示,手機切換橫豎屏不能用。
第一步:在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的。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.