How to set underline text on textview?
You have to use SpannableString for that :
String mystring=new String("Hello.....");
SpannableString content = new SpannableString(mystring);
content.setSpan(new UnderlineSpan(), 0, mystring.length(), 0);
yourtextview.setText(content);
Update : You can refer my answer on Underling TextView's here in all possible ways.
Following are the some approaches for underlined text in android:
1st Approach
You can define your string in strings.xml
<string name="your_string"><u>Underlined text</u></string>
And use that string in your xml
file
<TextView
android:id="@+id/txt_underlined"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="@string/your_string"/>
Or you can use that string in your Activity/Fragment
txtView.setText(R.string.your_string);
2nd Approach
To underline the text in TextView, you can use SpannableString
String text="Underlined Text";
SpannableString content = new SpannableString(text);
content.setSpan(new UnderlineSpan(), 0, text.length(), 0);
txtView.setText(content);
3rd Approach
You can make use of setPaintFlags method of TextView to underline the text of TextView.
txtView.setPaintFlags(mTextView.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
txtView.setText("Underlined Text");
4th Approach
Make use of Html.fromHtml(htmlString)
;
String htmlString="<u>Underlined Text</u>";
txtView.setText(Html.fromHtml(htmlString));
Or
txtView.setText(Html.fromHtml("<u>underlined</u> text"));
Note:
If you have added this line android:textAllCaps="true"
in your layout, then none of the above will work. For that, you have to define your string in Caps and then any of the above approach.
Use this
tvHide.setPaintFlags(tvHide.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
Android supports string formatting using HTML tags in the strings xml. So the following would work:
<string name="label_testinghtmltags"><u>This text has an underscore</u></string>
Then you just use it as you normally would. You can see more in the documentation here
Update:
To further expand on the answer, the documentation says:
... the
format(String, Object...)
andgetString(int, Object...)
methods strip all the style information from the string. . The work-around to this is to write the HTML tags with escaped entities, which are then recovered with fromHtml(String), after the formatting takes place
For example, the resulting string from the following code snippet will not show up as containing underscored elements:
<string name="html_bold_test">This <u>%1$s</u> has an underscore</string>
String result = getString(R.string.html_bold_test, "text")
However the result from the following snippet would contain underscores:
<string name="html_bold_test">This <u> %1$s </u> has an underscore</string>
String result = Html.fromHtml(getString(R.string.html_bold_test, "text"))