27

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
  • 51,611
  • 92
  • 240
  • 358
  • 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

40

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

textView.setText(Html.fromHtml("this is <u>underlined</u> text"));
kameny
  • 2,457
  • 4
  • 29
  • 40
33

Define a string as:

<resources>
    <string name="your_string">This is an <u>underline</u> text demo for TextView.</string>
</resources>
Pang
  • 9,073
  • 146
  • 84
  • 117
Paresh Mayani
  • 125,853
  • 70
  • 238
  • 294
  • 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,252
  • 1
  • 36
  • 55
3
tobeunderlined= <u>some text here which is to be underlined</u> 

textView.setText(Html.fromHtml("some string"+tobeunderlined+"somestring"));
mmBs
  • 8,126
  • 6
  • 40
  • 44
2

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
  • 52,662
  • 21
  • 188
  • 195