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

C# Xamarin Android WebView横屏适配:横屏内容溢出需滚动如何解决

解决方案

问题根因

当前使用自定义渲染器的思路是正确的,问题出在两点:

  1. 适配逻辑仅在WebView初始化时执行一次,屏幕旋转后WebView可视区域尺寸变化,没有触发重新适配
  2. 此前测试的JS代码使用screen.width/screen.height取的是设备物理屏幕的完整尺寸,没有排除系统状态栏、导航栏的占用,和WebView实际可用尺寸不匹配

步骤1:修改自定义渲染器

调整CustomWebViewRenderer逻辑,添加尺寸变化监听,旋转时自动重新执行适配:

public class CustomWebViewRenderer : WebViewRenderer
{
    public CustomWebViewRenderer(Context context) : base(context) { }

    protected override void OnElementChanged(ElementChangedEventArgs<WebView> e)
    {
        base.OnElementChanged(e);
        if (Control != null)
        {
            Control.Settings.BuiltInZoomControls = true;
            Control.Settings.DisplayZoomControls = false;
            Control.Settings.SetSupportZoom(true);
            Control.Settings.LoadWithOverviewMode = true;
            Control.Settings.UseWideViewPort = true;
            // 启用JS支持
            Control.Settings.JavaScriptEnabled = true;
            // 初始化时执行一次适配
            AdjustWebViewSize();
            // 监听WebView尺寸变化,旋转时自动触发适配
            Control.LayoutChange += (s, args) => AdjustWebViewSize();
        }
    }

    // 重新适配页面尺寸
    private void AdjustWebViewSize()
    {
        if (Control == null) return;
        // 取WebView实际可用的宽高
        int width = Control.MeasuredWidth;
        int height = Control.MeasuredHeight;
        // 执行JS更新页面根元素宽高
        Control.EvaluateJavascript($"document.documentElement.style.width = '{width}px';", null);
        Control.EvaluateJavascript($"document.documentElement.style.height = '{height}px';", null);
    }

    // 监听屏幕旋转配置变化
    protected override void OnConfigurationChanged(Configuration newConfig)
    {
        base.OnConfigurationChanged(newConfig);
        AdjustWebViewSize();
    }
}

步骤2:优化XAML布局

StackLayout在子控件尺寸动态变化时的适配优先级低于Grid,替换成Grid布局避免尺寸传递异常,同时实现关闭按钮悬浮在直播流上层,不占用显示空间:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage 
    NavigationPage.HasNavigationBar="False"
    xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:androidclient="clr-namespace:AndroidClient"
             x:Class="AndroidClient.LiveViewPage">
    <Grid HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
        <androidclient:CustomWebView x:Name="Browser"  
                  VerticalOptions="FillAndExpand" 
                  HorizontalOptions="FillAndExpand"/>
        <Button  x:Name="ExitFullScreenBtn" Clicked="ExitFullScreenBtn_Clicked"
                 HorizontalOptions="End" VerticalOptions="Start" WidthRequest="50"
                 Text="X"/>
    </Grid>
</ContentPage>

补充说明

原有后台C#代码无需调整,保持现有逻辑即可。修改完成后横竖屏切换时都会自动重新计算WebView可用尺寸,同步更新页面宽高实现无滚动适配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 03:45:07