53

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
  • 37,241
  • 25
  • 195
  • 267
Pratik Patel
  • 551
  • 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

126

Try this code:

textview.setPaintFlags(textview.getPaintFlags()| Paint.UNDERLINE_TEXT_FLAG);
Rumit Patel
  • 8,830
  • 18
  • 51
  • 70
yahya.can
  • 1,790
  • 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,324
  • 4
  • 28
  • 54
21

Kotlin way

textview.paintFlags = Paint.UNDERLINE_TEXT_FLAG
Levon Petrosyan
  • 8,815
  • 8
  • 54
  • 65
Aditya Patil
  • 1,287
  • 12
  • 19
20

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);
Deepika Lalra
  • 201
  • 1
  • 2
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
  • 8,057
  • 8
  • 35
  • 54
Bernard Covic
  • 1,489
  • 1
  • 10
  • 6
1

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
  • 179
  • 8
1

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
  • 668
  • 8
  • 9