Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I bind an HTML string to a webview in an Android app?

I currently have a android:TextView which is bound to a string which may or may not contain HTML.

<TextView
        android:text="Medium Text"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:autoLink="all"
        android:padding="10dp"
        style="@style/ListItemText"
        local:MvxBind="Text Answer" />

Somehow I need to be able to display this text with the html rendered. So I thought I would switch the TextView to a WebView and bind the same string to the WebView. I'm fairly new to Android dev, so I'm not sure if this can even be done or if there is another way I should be approaching this.

like image 699
Mark Erickson Avatar asked Feb 16 '23 01:02

Mark Erickson


1 Answers

For small amounts of HTML text, you can use the TextFormatted property of a TextView - usually with a ValueConverter which will perform the HTML parsing (using Html.FromHtml(input))

public class FromHtmlValueConverter : MvxValueConverter<string>
{
   protected override object Convert(string value, Type targetType, object parameter, CultureInfo culture)
   {
       return Html.FromHtml(value);
   }
}

<TextView
    android:text="Medium Text"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:autoLink="all"
    android:padding="10dp"
    style="@style/ListItemText"
    local:MvxBind="TextFormatted FromHtml(Answer)" />

For rendering a full WebView, then you'll need to add a custom binding - or inherit and provide a custom property - in order to call LoadData when the VM changes. This is similar to the inheritance technique used for UIWebView in Dynamic Binding UIWebView in MVVMCross

like image 57
Stuart Avatar answered Mar 15 '23 08:03

Stuart