Xamarin表单 - 在Android上的webview中显示本地html文件

时间:2018-01-11 10:41:39

标签: webview xamarin.forms

听起来很简单,但出于某种原因,这对我不起作用。我有以下代码:

string rootPath = DependencyService.Get<IBaseUrl>().Get();
var source = new UrlWebViewSource
{
    Url = System.IO.Path.Combine(rootPath, "Index.html")
};

browser.Source = source;

在android上实现IBaseUrl的代码是

public class BaseUrl : IBaseUrl
{
    public string Get()
    {
        return "file:///android_asset/Content/";

    }
}

还尝试从网址中删除“内容”,但仍无效。

1 个答案:

答案 0 :(得分:1)

您可以从pcl阅读内容并创建html源代码:

public static string GetFileContent(string fileName) {
            string content;
            var assembly = typeof(App).GetTypeInfo().Assembly;
            var stream = assembly.GetManifestResourceStream(fileName);
            if (stream == null) return null;
            using (var reader = new StreamReader(stream)) content = reader.ReadToEnd();

            return content;
        }

void CreateSource(){
     var htmlSource = new HtmlWebViewSource();
     htmlSource.Html = GetFileContent("AppName.Resources.Content.html");
     browser.Source = htmlSource;
}

这适用于iOS和Android。