Can I underline text in an Android layout?
The "accepted" answer above does NOT work (when you try to use the string like textView.setText(Html.fromHtml(String.format(getString(...), ...)))
.
As stated in the documentations you must escape (html entity encoded) opening bracket of the inner tags with <
, e.g. result should look like:
<resource>
<string name="your_string_here">This is an <u>underline</u>.</string>
</resources>
Then in your code you can set the text with:
TextView textView = (TextView) view.findViewById(R.id.textview);
textView.setText(Html.fromHtml(String.format(getString(R.string.my_string), ...)));
You can try with
textview.setPaintFlags(textview.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
It can be achieved if you are using a string resource xml file, which supports HTML tags like <b></b>
, <i></i>
and <u></u>
.
<resources>
<string name="your_string_here"><![CDATA[This is an <u>underline</u>.]]></string>
</resources>
If you want to underline something from code use:
TextView textView = (TextView) view.findViewById(R.id.textview);
SpannableString content = new SpannableString("Content");
content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
textView.setText(content);
Strings.xml file content:
<resource>
<string name="my_text">This is an <u>underline</u>.</string>
</resources>
Layout xml file shold use the above string resource with below properties of textview, as shown below:
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="@string/my_text"
android:selectAllOnFocus="false"
android:linksClickable="false"
android:autoLink="all"
/>