该问题出现在Android上。
我实现了一个自定义渲染器,用于WebView
根据其内容调整高度请求的能力。
我从Xamarin论坛帖子中获取了这个解决方案。
[assembly: ExportRenderer(typeof(AutoHeightWebView), typeof(AutoHeightWebViewRenderer))]
namespace MyProject.Droid.Renderers
{
public class AutoHeightWebViewRenderer : WebViewRenderer
{
public AutoHeightWebViewRenderer(Context context): base(context) {}
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
{
base.OnElementChanged(e);
if (e.NewElement is AutoHeightWebView webViewControl)
{
if (e.OldElement == null)
{
Control.SetWebViewClient(new ExtendedWebViewClient(webViewControl));
}
}
}
class ExtendedWebViewClient : Android.Webkit.WebViewClient
{
private readonly AutoHeightWebView _control;
public ExtendedWebViewClient(AutoHeightWebView control)
{
_control = control;
}
public override async void OnPageFinished(Android.Webkit.WebView view, string url)
{
if (_control != null)
{
int i = 10;
while (view.ContentHeight == 0 && i-- > 0) // wait here till content is rendered
{
await System.Threading.Tasks.Task.Delay(100);
}
_control.HeightRequest = view.ContentHeight;
}
base.OnPageFinished(view, url);
}
}
}
}
基于某种逻辑,我更改了WebView
的源代码,并使用自定义渲染器调整视图大小。
当尺寸增加时,这是有效的,但当内容尺寸小于之前的尺寸时则不行...
更明确地说,如果将WebView
的源代码设置为高度为200像素的HTML文件,并将其更改为高度为1000像素的HTML文件,则可以正常工作并且可以看到所有内容。但是,如果尝试返回到200像素的HTML文件,则会在底部留下800像素的空白空间,因为视图没有更改view.ContentHeight
的值,仍然保持在1000像素的值上。
我遵循了这个问题/线程,但没有找到解决此问题的解决方案:https://github.com/xamarin/Xamarin.Forms/issues/1711
我已经看到许多关于Android的主题,称我们需要重新创建Webview。是否有其他解决方案?
WebView
包装在一个Grid
中,并将RowDefinition
设置为Auto
吗? - FabriBertani