代码之家  ›  专栏  ›  技术社区  ›  Christian

将存储在Xamarin.Forms中的html资产加载到webview中

  •  0
  • Christian  · 技术社区  · 7 年前

    webview in Xamarin.Android 这建议在每个受支持的平台上编写特定于平台的代码。

    理想情况下,我希望将html存储在 /assets/ 在Xamarin.Forms中,而不是为每个操作系统存储一次。

    我希望有一种更简单的方法,只需将资产存储在Xamarin.Forms中。可能吗?

    2 回复  |  直到 7 年前
        1
  •  1
  •   Christian    7 年前

    我找到了一种让它工作的方法:

    在里面 RightClickOnProject/Properties/Resources HtmlFile.txt -文件。

    我将WebView添加到 xaml 通过:

    <ContentPage.Content>
        <StackLayout>
            <WebView x:Name="Web" VerticalOptions="FillAndExpand" />                     
        </StackLayout>
    </ContentPage.Content>
    

    public partial class OurPage: ContentPage
    {
        public OurPage()
        {
            InitializeComponent();
    
            Web.Source = new HtmlWebViewSource{Html = Properties.Resources.HtmlFile};
        }
    }
    
        2
  •  0
  •   FreakyAli    7 年前

    如果我是对的,你可以使用资产文件夹中的嵌入文件,然后使用 System.IO

    • 将要读取的文件添加到portable类中所需的文件夹中,并确保 .

    • GetManifestResourceStream WorkingWithFiles 文件名为PCLTextResource.txt,因此资源ID与files.PCLTextResource.txt一起工作。现在,为了获得所需的文件数据,您只需要这样做:

       var assembly = IntrospectionExtensions.GetTypeInfo(typeof(LoadResourceText)).Assembly;
       Stream stream = assembly.GetManifestResourceStream("WorkingWithFiles.PCLTextResource.txt");
       string text = "";
       using (var reader = new System.IO.StreamReader (stream)) {
       text = reader.ReadToEnd ();
       }
      

      哪里 LoadResourceText 是我使用此代码获取当前程序集的cs文件。请注意,这应该是您刚才添加的嵌入资源所在的相同程序集,并且 WorkingWithFiles.PCLTextResource.txt 是嵌入资源的程序集路径,例如:如果程序集名称为 Foo Asset Foo.Asset.Your_File.txt

    • 完成所有这些之后,简单的部分就开始了,在WebView页面中定义 HtmlWebViewSource 并将其指定为WebView和Vola的源文件!您已经从您的文件中加载了数据。

          var browser = new WebView();
          var htmlSource = new HtmlWebViewSource();
          htmlSource.Html = ;//your html string here
          browser.Source = htmlSource;
      

    How to work with files 了解更多信息。