前言
最近才发现MAUI Blazor Android存在输入框软键盘遮挡这个问题,搜索了一番,原来这是安卓webview一个由来已久的问题,还好有大佬提出了解决方案 AndroidBug5497Workaround,但是这是Java代码,MAUI中需要做一些小的修改,修改一些方法名还有类的明确引用。废话不多说,直接上代码。
解决方案
第一步
将下面的代码添加到Platforms/Android文件夹中,注意using ,一个也不能少,我最开始就是因为缺少using Rect = Android.Graphics.Rect;
没有成功。命名空间也别忘了更改。
using Android.App;
using Android.Widget;
using static Android.Resource;
using Rect = Android.Graphics.Rect;
using View = Android.Views.View;
namespace MauiApp3.Platforms.Android
{
public class AndroidBug5497Workaround
{
// For more information, see https://code.google.com/p/android/issues/detail?id=5497
// To use this class, simply invoke assistActivity() on an Activity that already has its content view set.
public static void AssistActivity(Activity activity)
{
new AndroidBug5497Workaround(activity);
}
private View mChildOfContent;
private int usableHeightPrevious;
private FrameLayout.LayoutParams frameLayoutParams;
private AndroidBug5497Workaround(Activity activity)
{
FrameLayout content = (FrameLayout)activity.FindViewById(Id.Content);
mChildOfContent = content.GetChildAt(0);
mChildOfContent.ViewTreeObserver.GlobalLayout += (s, o) => PossiblyResizeChildOfContent();
frameLayoutParams = (FrameLayout.LayoutParams)mChildOfContent.LayoutParameters;
}
private void PossiblyResizeChildOfContent()
{
int usableHeightNow = ComputeUsableHeight();
if (usableHeightNow != usableHeightPrevious)
{
int usableHeightSansKeyboard = mChildOfContent.RootView.Height;
int heightDifference = usableHeightSansKeyboard - usableHeightNow;
if (heightDifference > (usableHeightSansKeyboard / 4))
{
// keyboard probably just became visible
frameLayoutParams.Height = usableHeightSansKeyboard - heightDifference;
}
else
{
// keyboard probably just became hidden
frameLayoutParams.Height = usableHeightSansKeyboard;
}
mChildOfContent.RequestLayout();
usableHeightPrevious = usableHeightNow;
}
}
private int ComputeUsableHeight()
{
Rect r = new Rect();
mChildOfContent.GetWindowVisibleDisplayFrame(r);
return (int)(r.Bottom - r.Top);// 全屏模式下: return r.bottom
}
}
}
第二步
Platforms/Android/MainActivity.cs中添加以下代码
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
AndroidBug5497Workaround.AssistActivity(this);
}
后记
网上还有一些其他人针对底部导航栏和华为的修复,貌似加的也不多,参考着改改就能用了