.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端具体实现:
实现步骤
- 在Android项目中创建名为
DeviceSafeInsetsService.android.cs的文件 - 编写如下兼容不同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
相关产品推荐
相关产品推荐

