沉浸式模式退出问题咨询:附进入沉浸式模式实现代码
Fixing Immersive Mode Exit Issues in Android (C#)
Hey there! Let's work through how to properly exit immersive mode based on the code you've shared.
First, let's recap what your current code does: you're using bitwise OR (|=) to add multiple immersive-related SystemUiFlags to your decor view. To exit this mode, we need to reverse that action by removing those exact flags using a bitwise AND NOT (&= ~) operation.
Step-by-Step Solution Code
Here's the code you can use to exit immersive mode completely:
// Get the current decor view var decorView = Window.DecorView; // Capture the current UI visibility state var currentUiOptions = (int)decorView.SystemUiVisibility; // Remove all the immersive-related flags you previously set var newUiOptions = currentUiOptions & ~(int)( SystemUiFlags.LowProfile | SystemUiFlags.Fullscreen | SystemUiFlags.HideNavigation | SystemUiFlags.Immersive | SystemUiFlags.ImmersiveSticky ); // Apply the updated UI visibility state decorView.SystemUiVisibility = (StatusBarVisibility)newUiOptions;
Key Notes to Keep in Mind
- Bitwise Operations Explained: The
~operator flips the bits of the flag combination, and&=keeps only the flags that weren't part of your immersive setup. This effectively undoes the flags you added earlier. - ImmersiveSticky Behavior: If you used
ImmersiveSticky, the system normally hides the status/navigation bars again after user interaction. But to fully exit back to the normal UI state, you must explicitly remove this flag—otherwise, the sticky behavior will persist. - Main Thread Requirement: Make sure you run this code on the main thread (all UI operations in Android require this). If you're triggering this from a background task, use
RunOnUiThread()to wrap the code. - Triggering the Exit: You can tie this code to user actions like a button click, back press, or any other event where you want to exit immersive mode. For example, overriding
OnBackPressed():public override void OnBackPressed() { // Exit immersive mode first var decorView = Window.DecorView; var currentUiOptions = (int)decorView.SystemUiVisibility; var newUiOptions = currentUiOptions & ~(int)( SystemUiFlags.LowProfile | SystemUiFlags.Fullscreen | SystemUiFlags.HideNavigation | SystemUiFlags.Immersive | SystemUiFlags.ImmersiveSticky ); decorView.SystemUiVisibility = (StatusBarVisibility)newUiOptions; // Then proceed with default back press behavior base.OnBackPressed(); }
Bonus: Verifying the State
If you want to check if you're currently in immersive mode before exiting, you can use a bitwise AND to check for the presence of the flags:
var isImmersive = ((int)decorView.SystemUiVisibility & (int)SystemUiFlags.Immersive) != 0; if (isImmersive) { // Run the exit code here }
内容的提问来源于stack exchange,提问作者Ali
相关产品推荐
相关产品推荐

