使用WebView Xamarin表单加载本地HTML

use*_*961 3 c# webview xamarin xamarin.forms

我正在尝试使用Xamarin表单在Web视图中加载本地HTML页面。我可以在开发文档中使用基本示例,尽管可以加载URL,但无法加载自己的HTML页面。这仅需要通过Android完成,因此无需担心IOS和Windows。

Xaml:

 <WebView
    x:Name="webviewjava"></WebView>
Run Code Online (Sandbox Code Playgroud)

后面的代码:

 public partial class javscriptExample : ContentPage
{
    public interface IBaseUrl { string Get(); }
    public javscriptExample()
    {
        InitializeComponent();
        var source = new HtmlWebViewSource();

        source.BaseUrl = DependencyService.Get<IBaseUrl>().Get();

        webviewjava.Source = source;
    }
}
Run Code Online (Sandbox Code Playgroud)

平台特定文件(LocalFile.cs):请注意,此文件已被设置为Android资源。

 [assembly: Dependency(typeof(LocalFiles))]
namespace maptesting.Droid
{
    public class LocalFiles: IBaseUrl
    {
        public string Get()
        {
            return "file:///android_asset/";
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

在资产文件夹下有一个“ TestWebPage.html”,也已设置为Android资产。

尽管我不知道问题出在哪里,但我已通过调试将其放置,并且基本URL重新变空。为了清楚起见,我没有找到文件,屏幕只是空白。另外,我不确定这是否有所作为。LocalFiles.cs文件中的“ IBaseUrl”上没有突出显示语法。因此,我不确定它是否可以“看到”它。

有任何想法吗?

Kon*_*esh 8

我也遇到同样的问题,但是我通过以下方式解决了

使用“ UrlWebViewSource”代替“ HtmlWebViewSource”

var urlSource = new UrlWebViewSource();

string baseUrl = DependencyService.Get<IWebViewBaseUrl>().GetBaseUrl();
string filePathUrl = Path.Combine(baseUrl, "imprint.html");
urlSource.Url = filePathUrl;
WebBrowser.Source = urlSource;
Run Code Online (Sandbox Code Playgroud)


Vim*_*din 5

您必须检查 Build Action = BundleResource 的文件属性

尝试使用此代码加载本地 html 文件

var source = new HtmlWebViewSource();
        string url = DependencyService.Get<IBaseUrl>().GetBaseUrl();
        string TempUrl = Path.Combine(url, "terms.html");
        source.BaseUrl = url;
        string html;
        try
        {
            using (var sr = new StreamReader(TempUrl))
            {
                html = sr.ReadToEnd();
                source.Html = html;
            }
        }
        catch(Exception ex){
            Console.WriteLine(ex.Message);
        }
Run Code Online (Sandbox Code Playgroud)

然后必须提供每个平台的接口实现

iOS系统

[assembly: Dependency(typeof(BaseUrl))]
namespace yournamespace
{
   public class BaseUrl: IBaseUrl
   {
      public string GetBaseUrl()
      {
        return NSBundle.MainBundle.BundlePath;
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

安卓

[assembly: Dependency (typeof(BaseUrl))]
 namespace yournamespace {
   public class BaseUrl_Android : IBaseUrl {
      public string Get() {
        return "file:///android_asset/";
     } 
   }
 }
Run Code Online (Sandbox Code Playgroud)


Jon*_*dle 3

WebView.BaseUrl只告诉WebView从哪里开始查找文件。它是“网站”的根文件夹。默认情况下,浏览器会加载该文件index.html,因此如果您将文件重命名为index.html我相信它应该会自动加载。

我认为这也应该是可能的:

webviewjava.BaseUrl = DependencyService.Get<IBaseUrl>().Get();
webviewjava.Source = "TestWebPage.html";
Run Code Online (Sandbox Code Playgroud)

这里你说的是“使用这个位置作为查找文件的默认位置”和“查找这个文件并将其用作 HTML 的源”。