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

与世无争的帅哥 提交于 2019-12-22 09:10:17

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/19280053/how-can-i-bind-an-html-string-to-a-webview-in-an-android-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!