Android Activity旋轉螢幕橫屏實現全屏方法
阿新 • • 發佈:2018-12-31
activity在豎屏的時候,頂部會有狀態列,頂部會有ToolBar,現在需求是,旋轉螢幕以後,橫屏狀態下 整個介面是以全屏狀態顯示,隱藏ToolBar,不顯示螢幕最頂部的狀態列
首先,在AndroidManiFest裡面設定Activity的屬性:
<activity android:name=".MainActivity" android:configChanges="keyboardHidden|orientation|screenSize" android:screenOrientation="sensor" />
然後,在Activity中重寫onConfigurationChanged方法,程式碼如下:
private boolean portrait; @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); portrait = newConfig.orientation == Configuration.ORIENTATION_PORTRAIT; tryFullScreen(!portrait); } private void tryFullScreen(boolean fullScreen) { if這樣就能實現自動旋轉螢幕,並且全屏的需求了(activity instanceof AppCompatActivity) { ActionBar supportActionBar = ((AppCompatActivity) activity).getSupportActionBar(); if (supportActionBar != null) { if (fullScreen) { supportActionBar.hide(); } else { supportActionBar.show(); } } } setFullScreen(fullScreen);} private void setFullScreen(boolean fullScreen) { WindowManager.LayoutParams attrs = getWindow().getAttributes(); if (fullScreen) { attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN; getWindow().setAttributes(attrs); getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS); } else { attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN); getWindow().setAttributes(attrs); getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS); } }