Member-only story
Android: underlined text in a TextView
There are different ways to achieve underlined text in an Android TextView and you can choose em based in the result you want to score.
Since Android supports some html tags inside string resources, you can define underlined text inside strings.xml file as follows:
<u>This is my underlined text</u>
or
I just want to underline <u>this</u> word
You can do the same programmatically.
If you want to underline the whole text the most proper and straightforward way is to use paint flags (this flags handle how the view is drawn). This can be simply done by setting Paint.UNDERLINE_TEXT_FLAG ad follow
textView.setPaintFlags(textView.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
You can also underline a portion of the text via code, it can be done by creating a SpannableString and then setting it as the TextView text property:
SpannableString text = new SpannableString("Voglio sottolineare solo questa parola");text.setSpan(new UnderlineSpan(), 25, 6, 0);textView.setText(text);
The void setSpan(Object what, int start, int end, int flags) method takes in the span type (what, in this case UnderlineSpan) the start index(start), the end index (end) and some flags we’re not using this time.
This story is also available on xabaras.it (in Italian)