前言 最近才發現MAUI Blazor Android存在輸入框軟鍵盤遮擋這個問題,搜索了一番,原來這是安卓webview一個由來已久的問題,還好有大佬提出瞭解決方案 AndroidBug5497Workaround,但是這是Java代碼,MAUI中需要做一些小的修改,修改一些方法名還有類的明確引用 ...
前言
最近才發現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);
}
後記
網上還有一些其他人針對底部導航欄和華為的修複,貌似加的也不多,參考著改改就能用了