How can I define underlined text in an Android layout xml file?

1 upvote
  flag
To get an Easy One Line Solution for the same see my answer below. – gprathour

17 Answers 11

up vote 833 down vote accepted

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">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);
33 upvote
  flag
Hi, i tried the above resource xml code and it diddnt work. it continued to display the <u>underline</u> as a plain text – jonney
4 upvote
  flag
See also: android.text.Html.fromHtml( ) which returns a Spanned. – Mark Renouf
3 upvote
  flag
You should type it in strings.xml file itself, not doing it by add button. Otherwise you will get this &lt;u&gt; in your strings.xml file and <u>underline</u> in your code – gdrt
2 upvote
  flag
I have come across cases when underlying through <u> tags does not work, e.g. sometimes if you are using a custom font. However, underlying programmatically by UnderlineSpan has yet to fail on me, so I would recommend it as the most reliable solution. – Giulio Piancastelli
upvote
  flag
Writing in the xml resource file did not work for me on Android SDK 4.0.3 . But Java code worked. Thank you – Nilesh
10 upvote
  flag
It won't show in editor, but when You start You app - it will be underlined. – jean d'arme
upvote
  flag
what if I want to have a bit of space between text and underline ? – Alex
upvote
  flag
FWIW, <u>text</u> worked for a string resource in an app running on Marshmallow. I entered it directly with a text editor, not a fancy text-escaping resource editor. – fadden
upvote
  flag
Don't use getString to fetch the string from your xml, use it directly e.g: tv.setText(R.string.your_html_string); Then it will work. – Gal Rom

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 &lt;, e.g. result should look like:

<resource>
    <string name="your_string_here">This is an &lt;u>underline&lt;/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), ...)));
2 upvote
  flag
<u>underlined here</u> works perfectly. &lt;u>underline&lt;/u> did not work. This is for Android 2.2. Maybe different versions interpret it differently. – user898763452
upvote
  flag
@autotravis which one is for 2.2? I did not tested it on older versions and it will be quite unfortunate if different versions handle it differently... Also at least current documentation states that it have to be escaped (link is in the answer). – Ognyan
upvote
  flag
I've tested <u>underlined</u> on android 2.3 and it works. &lt;u>underline&lt;/u> does not work for 2.3. The docs say "Sometimes you may want to create a styled text resource that is also used as a format string. Normally, this won't work because the String.format(String, Object...) method will 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." So I guess you would use the escaping if you run it through that String.format(...) method. – user898763452
upvote
  flag
@autotravis yes, you are correct. I use it with String.format(...). I've edited my answer, thank you for your feedback. – Ognyan
upvote
  flag
On 2.3 and 4.1 (only ones I tried so far) you can just use textView.setText(getText(R.string.text)) instead of having to use getString(), Html.fromHtml() and String.format(). – Roy Solberg
upvote
  flag
<u>underlined</u> works for me in v2.1 :) – happyhardik
upvote
  flag
not work as of sdk 19 – abedfar

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"
    />
3 upvote
  flag
Make sure you edit the string resource file inside the actual XML rather than inside the helper editing UI in Eclipse, at it will escape the <s. – Chris Rae

You can try with

textview.setPaintFlags(textview.getPaintFlags() |   Paint.UNDERLINE_TEXT_FLAG);
1 upvote
  flag
Maybe a minor point, but OP wanted this defined in XML layout file; otherwise, this is a great solution. – kwishnu
4 upvote
  flag
use this solution if you want to clear it – breceivemail
1 upvote
  flag
noOFTimesLinesCopied =noOfUPVotes; return thanks; – Killer
2 upvote
  flag
this solution can be used for a Button too – Rudy Kurniawan
1 upvote
  flag
amazing :) simple and perfect :) – Rohit Kumar
upvote
  flag
Thanks a lot :) – Woppi

I had a problem where I'm using a custom font and the underline created with the resource file trick (<u>Underlined text</u>) did work but Android managed to transform the underline to a sort of strike trough.

I used this answer to draw a border below the textview myself: //allinonescript.com/a/10732993/664449. Obviously this doesn't work for partial underlined text or multilined text.

I know this is a late answer, but I came up with a solution that works pretty well... I took the answer from Anthony Forloney for underlining text in code and created a subclass of TextView that handles that for you. Then you can just use the subclass in XML whenever you want to have an underlined TextView.

Here is the class I created:

import android.content.Context;
import android.text.Editable;
import android.text.SpannableString;
import android.text.TextWatcher;
import android.text.style.UnderlineSpan;
import android.util.AttributeSet;
import android.widget.TextView;

/**
 * Created with IntelliJ IDEA.
 * User: Justin
 * Date: 9/11/13
 * Time: 1:10 AM
 */
public class UnderlineTextView extends TextView
{
    private boolean m_modifyingText = false;

    public UnderlineTextView(Context context)
    {
        super(context);
        init();
    }

    public UnderlineTextView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        init();
    }

    public UnderlineTextView(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
        init();
    }

    private void init()
    {
        addTextChangedListener(new TextWatcher()
        {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after)
            {
                //Do nothing here... we don't care
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count)
            {
                //Do nothing here... we don't care
            }

            @Override
            public void afterTextChanged(Editable s)
            {
                if (m_modifyingText)
                    return;

                underlineText();
            }
        });

        underlineText();
    }

    private void underlineText()
    {
        if (m_modifyingText)
            return;

        m_modifyingText = true;

        SpannableString content = new SpannableString(getText());
        content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
        setText(content);

        m_modifyingText = false;
    }
}

Now... whenever you want to create an underlined textview in XML, you just do the following:

<com.your.package.name.UnderlineTextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:gravity="center"
    android:text="This text is underlined"
    android:textColor="@color/blue_light"
    android:textSize="12sp"
    android:textStyle="italic"/>

I have added additional options in this XML snippet to show that my example works with changing the text color, size, and style...

Hope this helps!

1 upvote
  flag
While this example works, I quickly realized that if you ever want to have additional control in XML that this just won't do... I have switched to a better solution that involves the following steps: 1) Subclass textview 2) Add support to underline the text via custom attributes to do the underlining as specified above. The only difference is that you only execute the underline code if the custom attribute is set. – Justin

try this code

in XML

<resource>
 <string name="my_text"><![CDATA[This is an <u>underline</u>]]></string> 
</resources> 

in Code

TextView textView = (TextView) view.findViewById(R.id.textview);
textView.setText(Html.fromHtml(getString(R.string.my_text)));

Good Luck!

Three ways of underling the text in TextView.

SpannableString

setPaintFlags(); of TextView

Html.fromHtml();

1st Approach

For underling the text in TextView you have to use SpannableString

String udata="Underlined Text";
SpannableString content = new SpannableString(udata);
content.setSpan(new UnderlineSpan(), 0, udata.length(), 0);//where first 0 shows the starting and udata.length() shows the ending span.if you want to span only part of it than you can change these values like 5,8 then it will underline part of it.
mTextView.setText(content);

2nd Approach

You can make use of setPaintFlags method of TextView to underline the text of TextView.

For eg.

mTextView.setPaintFlags(mTextView.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
mTextView.setText("This text will be underlined");

You can refer constants of Paint class if you want to strike thru the text.

3rd Approach

Make use of Html.fromHtml(htmlString);

String htmlString="<u>This text will be underlined</u>";
mTextView.setText(Html.fromHtml(htmlString));
upvote
  flag
I prefer using ScannableString. – Pedro Varela
1 upvote
  flag
The word is SpannableString not what you said Pedro Varela – Nepster
1 upvote
  flag
Loved the 2nd approach, neat and clean – Alberto M
1 upvote
  flag
This answer looks like //allinonescript.com/questions/8033316/… – Pang

One line solution

myTextView.setText(Html.fromHtml("<p><u>I am Underlined text</u></p>"));

It is bit late but could be useful for someone.

For Button and TextView this is the easiest way:

Button:

button = (Button) view.findViewById(R.id.btton1);
button.setPaintFlags(button.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);

Textview:

textView = (Textview) view.findViewById(R.id.textview1);
textView.setPaintFlags(textView.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
upvote
  flag
Easiest way to do it. great – Parth Anjaria
upvote
  flag
Btw this works with TextView, the answer just made it sound like it only worked with a Button and not a TextView. Great answer – Ed Lee
upvote
  flag
Here's the updated version thanks @EddieLee – awsleiman

One line solution:

textview.setPaintFlags(textview.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
upvote
  flag
simple solution & works great.. – Sayem
1 upvote
  flag
It works even for xamarin.android as follows ; viewHolder.Year.PaintFlags = Android.Graphics.PaintFlags.UnderlineText; – Ishwor Khanal

The most recent approach of drawing underlined text is described by Romain Guy on medium with available source code on GitHub. enter image description here

I used this xml drawable to create a bottom-border and applied the drawable as the background to my textview

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

<item>
    <shape android:shape="rectangle" >
        <solid android:color="@android:color/transparent" />
    </shape>
</item>

<item android:top="-5dp" android:right="-5dp" android:left="-5dp">
    <shape>
        <solid android:color="@android:color/transparent" />
        <stroke
                android:width="1.5dp"
                android:color="@color/pure_white" />
    </shape>
</item>

A simple and flexible solution in xml:

<View
  android:layout_width="match_parent"
  android:layout_height="3sp"
  android:layout_alignLeft="@+id/your_text_view_need_underline"
  android:layout_alignRight="@+id/your_text_view_need_underline"
  android:layout_below="@+id/your_text_view_need_underline"
  android:background="@color/your_color" />

check out the underscored clickable button style:

<TextView
    android:id="@+id/btn_some_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/btn_add_contact"
    android:textAllCaps="false"
    android:textColor="#57a0d4"
    style="@style/Widget.AppCompat.Button.Borderless.Colored" />

strings.xml:

<string name="btn_add_contact"><u>Add new contact</u></string>

Result:

enter image description here

  1. Go to strings.xml resource file
  2. Add a string in the resource file with an HTML underline tag where necessary.

strings.xml HTML underline sample

  1. Call the string resource ID in your Java code as following:
sampleTextView.setText(R.string.sample_string);
  1. The output should have the word "Stackoverflow" underlined.

Furthermore, the following code will not print the underline:

String sampleString = getString(R.string.sample_string);
sampleTextView.setText(sampleString);

Instead, use the following code to retain rich text format:

String sampleString = getText(R.string.sample_string);
sampleTextView.setText(sampleString);

"You can use either getString(int) or getText(int) to retrieve a string. getText(int) retains any rich text styling applied to the string." Android documentation.

Refer to the documentation: https://developer.android.com/guide/topics/resources/string-resource.html

I hope this helps.

Just use the attribute in string resource file e.g.

<string name="example"><u>Example</u></string>

Not the answer you're looking for? Browse other questions tagged or ask your own question.