28

Is there possibility in android to provide TextView some text in Java code with setText(text) function with basic tags like and to make marked words underlined ?

Damir
  • 54,277
  • 94
  • 246
  • 365
  • possible duplicate of [How to display HTML in TextView?](http://stackoverflow.com/questions/2116162/how-to-display-html-in-textview) – David Hedlund Jul 16 '12 at 11:34
  • [**This will help you,**](http://stackoverflow.com/questions/2394935/can-i-underline-text-in-an-android-layout) this is the example by which you can `underline` your textview text and also `italic`. – Nikunj Patel Dec 19 '11 at 07:26

5 Answers5

41

Yes, you can, use the Html.fromhtml() method:

textView.setText(Html.fromHtml("this is <u>underlined</u> text"));
kameny
  • 2,372
  • 4
  • 30
  • 40
34

Define a string as:

<resources>
    <string name="your_string">This is an <u>underline</u> text demo for TextView.</string>
</resources>
Pang
  • 9,564
  • 146
  • 81
  • 122
Paresh Mayani
  • 127,700
  • 71
  • 241
  • 295
  • Yes but you can use it for dynamic strings by using Html.fromHtml(), check above answer http://stackoverflow.com/a/8558246/379693 – Paresh Mayani Dec 01 '15 at 11:27
  • @PareshMayani but beware, there are tags not supported by `Html.fromHtml()`. Check this out http://stackoverflow.com/a/3150456/1987045 – rahulrvp Sep 28 '16 at 13:01
10

You can use UnderlineSpan from SpannableString class:

SpannableString content = new SpannableString(<your text>);
content.setSpan(new UnderlineSpan(), 0, content.length(), 0);

Then just use textView.setText(content);

josephus
  • 8,284
  • 1
  • 37
  • 57
3

Most Easy Way

TextView tv = findViewById(R.id.tv);
tv.setText("some text");
setUnderLineText(tv, "some");

Also support TextView childs like EditText, Button, Checkbox

public void setUnderLineText(TextView tv, String textToUnderLine) {
        String tvt = tv.getText().toString();
        int ofe = tvt.indexOf(textToUnderLine, 0);

        UnderlineSpan underlineSpan = new UnderlineSpan();
        SpannableString wordToSpan = new SpannableString(tv.getText());
        for (int ofs = 0; ofs < tvt.length() && ofe != -1; ofs = ofe + 1) {
            ofe = tvt.indexOf(textToUnderLine, ofs);
            if (ofe == -1)
                break;
            else {
                wordToSpan.setSpan(underlineSpan, ofe, ofe + textToUnderLine.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                tv.setText(wordToSpan, TextView.BufferType.SPANNABLE);
            }
        }
    }

If you want

- Clickable underline text?

- Underline multiple parts of TextView?

Then Check This Answer

Khemraj Sharma
  • 57,232
  • 27
  • 203
  • 212
3
tobeunderlined= <u>some text here which is to be underlined</u> 

textView.setText(Html.fromHtml("some string"+tobeunderlined+"somestring"));
mmBs
  • 8,421
  • 6
  • 38
  • 46