I'm trying to write a custom renderer for a Label to be able to use some HTML tags. I'm looking at an example I found, "Awesome Xamarin Forms Label with HTML Text Formatting", but I can't get it to work.
In Android I can change the text in my custom Label but without any HTML formatting. In iOS I can't change the text programmatically, only in XAML (but with the iOS simulator all other controls disappears!).
Any clues of what is wrong? Android code down below:
HtmlFormattedLabel.cs:
using Xamarin.Forms;
namespace TurfUserStatistics
{
public class HtmlFormattedLabel : Label
{
}
}
Android HtmlFormattedLabelRenderer.cs:
using Android.Content;
using Android.Text;
using Android.Widget;
using TurfUserStatistics;
using TurfUserStatistics.Droid;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
[assembly: ExportRenderer(typeof(HtmlFormattedLabel), typeof(HtmlFormattedLabelRenderer))]
namespace TurfUserStatistics.Droid
{
public class HtmlFormattedLabelRenderer : LabelRenderer
{
public HtmlFormattedLabelRenderer(Context context) : base(context)
{ }
public static void Initialize()
{ }
protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
{
base.OnElementChanged(e);
if (Control != null)
{
Control.SetText(Html.FromHtml(Element.Text.ToString()), TextView.BufferType.Spannable);
}
}
}
}
Android MainActivity.cs:
using Android.App;
using Android.Content.PM;
using Android.OS;
namespace TurfUserStatistics.Droid
{
[Activity(Label = "Turf User Statistics", Icon = "@drawable/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle bundle)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(bundle);
HtmlFormattedLabelRenderer.Initialize();
global::Xamarin.Forms.Forms.Init(this, bundle);
LoadApplication(new App());
}
}
}
Short version of XAML file:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
xmlns:local="clr-namespace:TurfUserStatistics;assembly=TurfUserStatistics"
x:Class="TurfUserStatistics.TUS_Main_Page"
Title="Turf User Statistics" >
<ContentPage.Content>
<ScrollView>
<StackLayout Padding="4">
<local:HtmlFormattedLabel x:Name="labelTest" Text="htmltext" FontSize="14">
</local:HtmlFormattedLabel>
</StackLayout>
</ScrollView>
</ContentPage.Content>
</ContentPage>
And in XAML.cs file:
labelTest.Text = "<html><body><b>bold</b> - <i>italic</i> - <u>underline</u></body></html>";