Styled text in TextView

The easiest way of having styled text in a TextView is to use HTML and it is very easy to do it:

mTextView.setText(Html.fromHtml("This is a < b >bold< /b > and < i >italics< /i > styled textview!"));

Share

Convert HTML special characters to normal text

Apache commons is once again the answer on “how to convert HTML special characters to normal text”.

Just include the commons-lang jar in your project and use only one line of code:
System.out.println(StringEscapeUtils.unescapeHtml3("special chars here"));

Commons Lang

The standard Java libraries fail to provide enough methods for manipulation of its core classes. Apache Commons Lang provides these extra methods.
Lang provides a host of helper utilities for the java.lang API, notably String manipulation methods, basic numerical methods, object reflection, concurrency, creation and serialization and System properties. Additionally it contains basic enhancements to java.util.Date and a series of utilities dedicated to help with building methods, such as hashCode, toString and equals.

Share

Use custom font in html/css

First declare your font in your css file:
@font-face {
font-family: a_cool_font_name;
src: url(‘path/to/cool/font.ttf’);
}

Then add it to your elements
p.custom_font{
font-family: a_cool_font_name; /* no .ttf */
}

ready :)

Share

Transform HTML entities to normal text

If you are parsing HTML encoded data like RSS, you’ll probably face HTML entities representing special characters like quotes, the & symbol and more.

It’s fine if you use the WebView to present them, but if you want to display the data somewhere else you have to transform them to “normal text”.

mTextView.setText(Html.fromHtml(htmlData).toString());
Share

WebView not displaying UTF-8 Data

If you have a WebView and you want to display html code, you will probably use the WebView.loadData function as seen in the example here.

String htmlCode = "<html><body><b>hello man!</b> non bold text</body></html>";
mWebView.loadData(htmlCode, "text/html", "UTF-8");

Done by the book, nice try, though it does not always work.
When the html code contains UTF data, you have to base encode all the html data.
You can accomplish that by using the loadDataWithBaseURL function.
example:

String htmlCode = "<html><body><b>hello man!</b> non bold text</body></html>";
mWebView.loadDataWithBaseURL(null, htmlCode, "text/html", "UTF-8", null);

Ready :)

Share