首页 > 解决方案 > 试图将 Html 字符串放入 Xamarin 中的 WebView

问题描述

Xamarin (Visual Studio 2017) 中的 WebView 有一点奇怪的问题

这种情况有效:
我在“OnCreate”事件中将 html 内容放入 webview,webview 显示“Hello”

这种情况不起作用:
我在 OnCreate 中创建一个按钮控件并分配一个单击事件。clickevent 触发所以这有效。但是尽管我使用完全相同的代码,但“Hello2”并未放入 WebView。

可能是什么问题呢?

<WebView xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:id="@+id/LocalWebView">
</WebView>


        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.activity_main); Android.Content.Context context = ApplicationContext;
            Android.Support.V7.Widget.Toolbar toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
            SetSupportActionBar(toolbar);


            //This works and shows: "Hello"
            WebView localWebView = FindViewById<WebView>(Resource.Id.LocalWebView);
            localWebView.SetWebViewClient(new WebViewClient()); // stops request going to Web Browser
            localWebView.LoadData("<html>Hello</html>", "text/html", "utf-8");



            Button button = new Button(context);
            button.Click += (sender, args) =>
            {
                //The click event fires but Hello2" is not put to the webview?
                Button btn = sender as Button;

                WebView localWebView2 = FindViewById<WebView>(Resource.Id.LocalWebView);
                localWebView2.SetWebViewClient(new WebViewClient()); // stops request going to Web Browser
                localWebView2.LoadData("<html>Hello2</html>", "text/html", "utf-8");
            };
        }

标签: c#androidxamarinwebview

解决方案


当我确实将宽度和高度放入 WebView 时,它现在可以工作了。奇怪的是“fill_parent”或“match_parent”没有展开 WebView。

<WebView xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="500px"
  android:layout_height="1000px"
  android:id="@+id/LocalWebView">
</WebView>


推荐阅读