Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Statically underline dynamic text in TextView

I would like to make a TextView to be entirely underlined but I can't use a text resource and <u> tag because it is dynamic text.

Related: Can I underline text in an android layout?

So far the only way I know to do this is at runtime. Is this really the only way? Is there a way I could do it in the XML files?

like image 388
700 Software Avatar asked Jan 12 '11 21:01

700 Software


People also ask

How do you underline text in TextView?

You can define the underlined text in an Android layout XML using a String Resouce XML file. In a string res file you have to use an HTML underline tag <u> </u> .

How to add underline in TextView in Android Studio?

You can also underline a portion of the text via code, it can be done by creating a SpannableString and then setting it as the TextView text property: SpannableString text = new SpannableString("Voglio sottolineare solo questa parola");text. setSpan(new UnderlineSpan(), 25, 6, 0);textView. setText(text);

How to underline TextView in Android Studio XML?

Just use <u> and <\u> in XML, and it's enough. in my case, android studio preview was not able to determine the html tag. but once i ran the project in real device, underlined text shown happily.

How to add underline in layout in android?

Navigate to the app > res > layout > activity_main. xml and add the below code to that file.


1 Answers

The easiest solution is probably to create a custom UnderLineTextView component deriving from TextView, override setText() and set the entire text as underlined, something like this (underline code from the link you referred to above):

@Override
public void setText(CharSequence text, BufferType type) {
    // code to check text for null omitted
    SpannableString content = new SpannableString(text);
    content.setSpan(new UnderlineSpan(), 0, text.length(), 0);
    super.setText(content, BufferType.SPANNABLE);

}

It's then just a matter of using your new component in the layout and setting the text as usual. The rest is handled automatically.

More info on custom components: http://developer.android.com/guide/topics/ui/custom-components.html

like image 96
peter3 Avatar answered Sep 27 '22 19:09

peter3