Good evening!
I have a textview and I take a text from a string into this View element.

Take out like this:

 MyTextView.setText(Html.fromHtml(getString(R.string.txt_0))) 

In string text is between

 <string name="txt_0"><![CDATA[ 

and

 ]]></string> 

And everything seems to be fine:

  <b>, <i>, <u>, <H2>, <br>, &nbsp 

And other HTML tags work. But, for example, I need to create a bulleted list:

 <ul> <li>элемент маркированного списка</li> </ul> 

But does not work. Or you need to put a separator line,

 <hr> 

but nothing again.

 <center> 

Also does not work. How to find out what works and what doesn't? And how to create a list line separator? This text along with the formatting will be in the SQLite database and pulled out from there.

  • Here you can see the class extending TagHandler with support for strike/s , ul/ol/li (including nested) and code tyk - Yuriy SPb
  • Stressed imports. I did not find the library: import com.android.msahakyan.expandablenavigationdrawer.AttributeGetter; - Alexey
  • This is my auxiliary class. You can replace it with ContextCompat.getColor() - Yuriy SPb
  • Contact: mSelectedItemView.setText (Html.fromHtml (getResources (). GetString (R.string.selected_item), null, new MyHtmlTagHandler ())); ? - Alexey
  • Yes, it seems, that’s all true - Yuriy Spb

2 answers 2

The fact is that not all HTML tags are supported. Here is a list of supported tags:

 <a> (supports attribute "href") <b> <big> <blockquote> <br> <cite> <dfn> <div> <em> <font> (supports attributes "color" and "face") <i> <img> (supports attribute "src". Note: you have to include an ImageGetter to handle retrieving a Drawable for this tag) <p> <small> <strong> <sub> <sup> <tt> <u> 

If you need more tags, you will have to do their own support, or use WebView instead of TextView

  • <blockquote> - line separator instead of <hr>. But it does not work correctly. The line is not horizontal, but vertical, next to the text that is included in this tag. And blue, although the color was not defined anywhere. - Alexey

In this case, <ul> and <li> just mark the text, and they need to be processed in the code. For this, there is an Html.TagHandler interface that needs to be implemented. For example, for the list:

 public class TagHandler implements Html.TagHandler { @Override public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) { if (!opening && tag.equals("ul")) { output.append("\n"); } if (opening && tag.equals("li")) { output.append("\n\u2022"); } } } 

It remains to call:

 TextView textView = (TextView) findViewById(R.id.text); textView.setText(Html.fromHtml(getResources().getString(R.string.text), null, new TagHandler())); 

Html documentation in TextView: https://developer.android.com/reference/android/text/Html.html