在Android開發中,隱藏標題欄和狀態欄是實現全屏顯示的常見需求。
一、隱藏標題欄
1、通過代碼隱藏
對于繼承自 AppCompatActivity 的 Activty,可在 onCreate() 方法中調用supportRequestWindowFeature 或 getSupportActionBar 方法來隱藏標題欄。
override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)// 隱藏標題欄方法1,必須在 setContentView 方法之前調用supportRequestWindowFeature(Window.FEATURE_NO_TITLE)setContentView(R.layout.activity_second)// 隱藏標題欄方法2, 調用位置沒有限制supportActionBar?.hide()}
對于普通 Activity,采用 requestWindowFeature 方法。
requestWindowFeature(Window.FEATURE_NO_TITLE)
2、通過主題隱藏
在 AndroidManifest.xml 文件中,為 <application> 標簽或特定 <activity> 標簽設置主題。
<applicationandroid:allowBackup="true"android:dataExtractionRules="@xml/data_extraction_rules"android:fullBackupContent="@xml/backup_rules"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:roundIcon="@mipmap/ic_launcher_round"android:supportsRtl="true"android:theme="@style/Theme.TwoApkSwitch"tools:targetApi="31">......<activity android:name=".SecondActivity" android:theme="@style/Theme.MaterialComponents.DayNight.NoActionBar"/>
二、隱藏狀態欄
1、通過代碼隱藏
如果隱藏狀態欄后,用戶下拉屏幕可能會重新顯示狀態欄,可以通過監聽onSystemUiVisibilityChange() 方法來重新隱藏。
/*** 隱藏狀態欄*/fun hideStateBar() {Log.d("SecondActivity", "version: ${Build.VERSION.SDK_INT}")if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {// Android 11及以上版本val controller = window.insetsControllerif (controller != null) {controller.hide(WindowInsets.Type.statusBars() or WindowInsets.Type.navigationBars())controller.systemBarsBehavior = WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE}} else {// Android 4.1及以上版本val decorView: View = window.decorViewval uiOptions: Int = View.SYSTEM_UI_FLAG_FULLSCREENdecorView.setSystemUiVisibility(uiOptions)// 用戶下拉屏幕可能會重新顯示狀態欄,可以通過監聽后重新隱藏decorView.setOnSystemUiVisibilityChangeListener {// 重新隱藏}// Android 4.0及以下版本window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN)}}
2、通過主題隱藏
在 AndroidManifest.xml 文件中,為 <application> 標簽或特定 <activity> 標簽設置主題。
可自定義主題,并在主題中添加 windowFullscreen 字段為 true。
<activity android:name=".SecondActivity"android:theme="@style/Theme.TwoApkSwitch.FullScreen"/>
在 themes.xml 中自定義隱藏狀態欄主題。
<style name="Theme.TwoApkSwitch.FullScreen" parent="Theme.MaterialComponents.DayNight.NoActionBar"><!-- Primary brand color. --><item name="colorPrimary">@color/purple_500</item><item name="colorPrimaryVariant">@color/purple_700</item><item name="colorOnPrimary">@color/white</item><!-- Secondary brand color. --><item name="colorSecondary">@color/teal_200</item><item name="colorSecondaryVariant">@color/teal_700</item><item name="colorOnSecondary">@color/black</item><!-- Status bar color. --><item name="android:statusBarColor">?attr/colorPrimaryVariant</item><!-- Customize your theme here. --><!-- 隱藏上方時間內容狀態欄--><item name="android:windowFullscreen">true</item></style>