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

.NET MAUI Android端屏幕底部多余空白问题及安全区实现咨询

.NET MAUI Android端DeviceSafeInsetsService实现方案

在.NET 8 MAUI应用中,多数Android设备底部的手势线会导致布局出现多余空白,类似iOS端的返回手势线问题。参考iOS端的解决方案,已定义跨平台部分类:

public partial class DeviceSafeInsetsService
{
    public partial double GetSafeAreaTop();
    public partial double GetSafeAreaBottom();
}

屏幕底部空白示例图

以下是该类的Android端具体实现:

实现步骤

  1. 在Android项目中创建名为DeviceSafeInsetsService.android.cs的文件
  2. 编写如下兼容不同Android版本的实现代码:
using Android.Views;
using Android.OS;
using Android.Content.Res;

public partial class DeviceSafeInsetsService
{
    public partial double GetSafeAreaTop()
    {
        var currentActivity = Platform.CurrentActivity;
        if (currentActivity == null) return 0;

        var windowInsets = currentActivity.Window.DecorView.RootWindowInsets;
        if (windowInsets == null) return 0;

        int topInset;
        if (Build.VERSION.SdkInt >= BuildVersionCodes.R)
        {
            topInset = windowInsets.GetInsets(WindowInsets.Type.StatusBars()).Top;
        }
        else
        {
            topInset = windowInsets.StableInsets.Top;
        }

        // 将像素转换为MAUI使用的DP单位
        return topInset / currentActivity.Resources.DisplayMetrics.Density;
    }

    public partial double GetSafeAreaBottom()
    {
        var currentActivity = Platform.CurrentActivity;
        if (currentActivity == null) return 0;

        var windowInsets = currentActivity.Window.DecorView.RootWindowInsets;
        if (windowInsets == null) return 0;

        int bottomInset;
        if (Build.VERSION.SdkInt >= BuildVersionCodes.R)
        {
            // 包含导航栏和输入法的Insets,可根据需求调整类型
            bottomInset = windowInsets.GetInsets(WindowInsets.Type.NavigationBars() | WindowInsets.Type.Ime()).Bottom;
        }
        else
        {
            bottomInset = windowInsets.StableInsets.Bottom;
        }

        // 将像素转换为MAUI使用的DP单位
        return bottomInset / currentActivity.Resources.DisplayMetrics.Density;
    }
}

使用说明

  • 建议在页面的OnAppearing生命周期方法之后调用这两个方法,确保Activity已完成初始化,能正确获取到WindowInsets
  • 代码中把Android返回的像素值转换为DP,和MAUI布局的单位保持一致
  • 若不需要处理输入法弹出的Insets,可将WindowInsets.Type.Ime()从GetSafeAreaBottom的参数中移除

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 11:35:57