xamarin.forms - 在 Xamarin 的 web 视图中将 CSS 样式表应用于 HTML 文档
问题描述
我有一个从 Xamarin WebView 中的服务器端呈现的 HTML 文档。我想将 CSS 样式表应用于 webview 中的 HTML 文档。
using (HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse())
{
using (Stream stream = httpResponse.GetResponseStream())
{
string response = (new StreamReader(stream)).ReadToEnd();
ArticleData article = JsonConvert.DeserializeObject<ArticleData>(JsonConvert.DeserializeObject<ArticleDetails>(response).d);
var htmlSource = new HtmlWebViewSource();
htmlSource.Html = "<html><head><link rel='stylesheet' type='text/css' href='Assets/Main.css' /></head><body>" + article.Html + "</body></html>";
webView.Source = htmlSource;
}
}
解决方案
根据您的代码,css 在 Assets 中。由于我没有article.Html
,我local.html
在 Assets 文件夹中创建了一个供参考。
本地.html:
<html>
<head>
<title>webViewSample</title>
<link rel="stylesheet" type="text/css" href="Main.css" />
</head>
<body>
<h1>Xamarin.Forms</h1>
<p>This is a local Android Html page</p>
<img src="XamarinLogo.png" />
</body>
</html>
主.css:
html,body{margin:0;padding:10px}
body, p, h1 {
font-family: 'Roboto';
}
使用依赖服务从 Assets 文件夹中加载 CSS 和 html 文件。
[assembly: Xamarin.Forms.Dependency(typeof(BaseUrl_Android))]
namespace App27.Droid
{
public class BaseUrl_Android : IBaseUrl
{
public string Get()
{
return "file:///android_asset/";
}
}
}
xml:
<StackLayout>
<Button Clicked="Button_Clicked"></Button>
<WebView x:Name="webView" HeightRequest="500"/>
</StackLayout>
后面的代码:
public interface IBaseUrl { string Get(); }
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
private void Button_Clicked(object sender, EventArgs e)
{
var htmlSource = new HtmlWebViewSource();
htmlSource.Html = "<html><head><link rel='stylesheet' type='text/css' href='Main.css' /></head><body>" + " <p><a href='local.html'>next page</a></p>" + "</body></html>";
htmlSource.BaseUrl = DependencyService.Get<IBaseUrl>().Get();
webView.Source = htmlSource;
}
}
推荐阅读
- css - 如何保持 div 可滚动溢出,但禁用任何其他触摸动作?
- angular - 如何在 Angular 9 中为同一个组件实现两个 html 文件?一款适合手机大小,一款适合台式机?
- node.js - 我们如何使用 process.stdout.on(....) 之外的变量?
- android - 带有屏幕截图的 FastPass 报告
- c - tcp header 和 payload 的实用函数——是否有内核
- python - 如何抓取画布标签,为什么它在我的浏览器中不可见?
- kubernetes - Kafka增量粘性再平衡
- html - 为什么网格模板行不能正常工作?
- javascript - 数组交叉连接 JavaScript 中的多个数组
- laravel - 我有类别和产品表。我想在 Laravel 中显示至少有 1 个产品的类别