0

How can I show html source as rendered in TextView or something else? I tried this:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    TextView tv = (TextView) findViewById(R.id.tv1);
    String s = "<img src=\"http://images2.layoutsparks.com/1/146278/purple-lotus-lovely-dew.jpg\"/>";
    Spanned sp = new SpannableString(s);

    tv.setText(Html.toHtml(sp));
}

But I got:

enter image description here

1 Answer 1

1

HTML support in a TextView is pretty limited, but here is an example of some of the things you can do:

https://github.com/brianjolly/TextFun

The key is escaping the opening bracket in your strings.xml

<string name="fun_text">I like &lt;font color=\'0x00b0f1\'>BLUE!&lt;/font> and &lt;b> Bold&lt;/b> and &lt;i> italic&lt;/i> and &lt;u> underline&lt;/u></string>

And then resetting the text like so:

String styledText = tv.getText().toString();
tv.setText(Html.fromHtml(styledText), TextView.BufferType.SPANNABLE);

The beauty of open source is you can see what Html.fromHtml() supports in the android source here:
https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/text/Html.java

If you're looking to do something more advanced take a look at WebView

Sign up to request clarification or add additional context in comments.

2 Comments

developer.android.com/guide/tutorials/views/hello-webview.html is very nice tutorial. Thank you for your answer...
@Brian why doesn't my string show correct color? it's <string name="formatting">&lt;div style="font-family: Arial, Helvetica, sans-serif; line-height: 25px; font-size: 17px;">&lt;p>&lt;strong>&lt;span style="color: #ff0000;">API docs&lt;/span>&lt;/strong>&lt;/p>&lt;/div></string>.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.