You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在.NET MAUI Android中实现透明状态栏并显示后方内容?

在Android平台上用.NET MAUI实现透明状态栏(内容可穿透显示)

要实现类似谷歌地图的透明状态栏效果(内容延伸至状态栏后方,同时保留可见导航栏),可以通过以下步骤用C#完成适配:

1. 修改Android项目主题配置

打开Platform/Android/Resources/values/styles.xml,更新AppTheme样式以配置状态栏基础属性:

<style name="AppTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar">
    <item name="android:windowActionBar">false</item>
    <item name="android:windowNoTitle">true</item>
    <!-- 开启状态栏透明与背景绘制 -->
    <item name="android:windowTranslucentStatus">true</item>
    <item name="android:windowDrawsSystemBarBackgrounds">true</item>
    <item name="android:statusBarColor">@android:color/transparent</item>
    <!-- 保持导航栏不透明且可见 -->
    <item name="android:windowTranslucentNavigation">false</item>
</style>

2. 在MainActivity中实现状态栏穿透逻辑

打开Platform/Android/MainActivity.cs,在OnCreate方法中添加版本适配代码,确保内容能延伸到状态栏下方:

protected override void OnCreate(Bundle savedInstanceState)
{
    base.OnCreate(savedInstanceState);

    // 适配Android 10及以上版本
    if (Build.VERSION.SdkInt >= BuildVersionCodes.Q)
    {
        Window.SetDecorFitsSystemWindows(false);
        Window.StatusBarColor = Android.Graphics.Color.Transparent;
        // 根据页面背景设置状态栏图标颜色(浅色背景用深色图标)
        Window.InsetsController?.SetSystemBarsAppearance((int)WindowInsetsControllerAppearance.LightStatusBars, (int)WindowInsetsControllerAppearance.LightStatusBars);
    }
    // 适配Android 5.0到Android 9
    else if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
    {
        Window.ClearFlags(WindowManagerFlags.TranslucentStatus);
        Window.AddFlags(WindowManagerFlags.DrawsSystemBarBackgrounds);
        Window.StatusBarColor = Android.Graphics.Color.Transparent;
        // 允许布局延伸至状态栏区域
        Window.DecorView.SystemUiVisibility = (StatusBarVisibility)(SystemUiFlags.LayoutStable | SystemUiFlags.LayoutFullscreen);
    }
}

3. MAUI页面布局调整

为让页面内容真正穿透状态栏,需移除默认的顶部内边距:

  • 若使用普通ContentPage,在页面构造函数中设置:
public MainPage()
{
    InitializeComponent();
    // 移除顶部内边距,让内容顶到状态栏
    Padding = new Thickness(0);
}
  • 若使用Shell,可在AppShell.xaml中隐藏默认导航栏(如需):
<Shell xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
       xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
       x:Class="YourAppName.AppShell"
       NavBarIsVisible="False">
    <!-- Shell内容 -->
</Shell>

注意事项

  • 状态栏图标颜色需根据页面背景调整:浅色背景开启LightStatusBars,深色背景则关闭该设置,避免图标不可见。
  • 如需调整导航栏颜色,可在styles.xml中添加android:navigationBarColor属性,或在MainActivity中通过Window.NavigationBarColor设置。

内容的提问来源于stack exchange,提问作者DanFlakes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 00:31:18