标签 html 类型未在 android Xamarin Forms 中呈现颜色 在 xaml 中

问题描述

当我们在 Label 中绑定 html 文本时,颜色不会在 android 中呈现。它只显示黑色。但在 IOS 中它工作正常。下面提到的代码片段,

查看代码

<Label Text="{Description}" TextType="Html" />
Description = System.Net.WebUtility.HtmlDecode(sampleHtmlText);

视图模型:

string sampleHtmlText = @"<p><br></p><p><b style=""font-size: 14px; color: rgb(150,185,16);"">What does the plan provide?</b></p><p><br></p><p><span style=""font-size: 14px;"">The plan is extremely comprehensive.</span></p></p>";

解决方法

在 Android 中,即使我们将 Type 设置为 Html ,也不会渲染内联 CSS 样式。所以我们可以使用 Nuget 的插件 HtmlLabelPlugin

在每个 Xamarin.Forms 项目(共享项目和 iOS、Android)中安装它。

iOS:AppDelegate.cs

HtmlLabelRenderer.Initialize();
global::Xamarin.Forms.Forms.Init();

Android:MainActivity.cs

HtmlLabelRenderer.Initialize();
global::Xamarin.Forms.Forms.Init(this,bundle);

在 xaml 中

xmlns:htmlLabel="clr-namespace:LabelHtml.Forms.Plugin.Abstractions;assembly=HtmlLabel.Forms.Plugin"
<htmlLabel:HtmlLabel x:Name="label"/>
 string sampleHtmlText = @"<span style='color: green'>What does the plan provide?</span>";

label.Text = sampleHtmlText;