48

I want to know how to set underline text to TextView in android? Please make a note that I don't have capability to set a strings.xml with pre-populated strings is there any way to add it with pure java code in Android.

Cœur
  • 34,719
  • 24
  • 185
  • 251
Pratik Patel
  • 501
  • 1
  • 4
  • 6
  • Please, take a look at this post: http://stackoverflow.com/questions/2394935/can-i-underline-text-in-an-android-layout – Yngwie89 Oct 20 '12 at 14:56
  • 4
    6 Ways - [Underline a TextView In Android](https://androidride.com/underline-a-textview-in-android/) – Vijay Ram Aug 18 '19 at 03:02

7 Answers7

119

Try this code:

   textview.setPaintFlags(textview.getPaintFlags()| Paint.UNDERLINE_TEXT_FLAG);
Pratik Butani
  • 56,749
  • 54
  • 254
  • 407
yahya.can
  • 1,720
  • 1
  • 11
  • 9
22

Here is the simplest way

TextView theTextView = new TextView(this);

theTextView.setText(Html.fromHtml("<u>Text to underline</u>"));
Vishal Pawar
  • 4,181
  • 3
  • 27
  • 54
18

Just try this:

TextView myTextView = new TextView(this);
SpannableString mySpannableString = new SpannableString("My String");
mySpannableString.setSpan(new UnderlineSpan(), 0, mySpannableString.length(), 0);
myTextView.setText(mySpannableString);
14

Kotlin way

textview.paintFlags = Paint.UNDERLINE_TEXT_FLAG
Levon Petrosyan
  • 7,024
  • 8
  • 51
  • 59
Aditya Patil
  • 714
  • 8
  • 13
9

i don't know if somebody is still interested in this topic, but i disovered that

textview.setTypeface(Typeface.NORMAL); did not work for me.

My solution was this snippet textView.setPaintFlags(0);

Gowthaman M
  • 7,600
  • 7
  • 31
  • 52
Bernard Covic
  • 1,359
  • 1
  • 9
  • 6
0

This is Kotlin extension to underline text

fun String.underLine(): SpannableString {
    val spanStr = SpannableString(this)
    spanStr.setSpan(UnderlineSpan(), 0, spanStr.length, 0)
    return spanStr
}
prsnlme
  • 121
  • 6
0

for kotlin .. put underline for textview or String Using HtmlCompat.fromHtml() method

val html = "<u> The text you want to underline </u>"
textview11.text = HtmlCompat.fromHtml(html, HtmlCompat.FROM_HTML_MODE_LEGACY)

for layout xml

<string name="text_underline"><u> The text you want to underline </u></string>
Mark Nashat
  • 380
  • 4
  • 6