Damir
Damir

Reputation: 56199

Can underline words in TextView text

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 ?

Upvotes: 28

Views: 58592

Answers (5)

Khemraj Sharma
Khemraj Sharma

Reputation: 58974

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

Upvotes: 3

Paresh Mayani
Paresh Mayani

Reputation: 128428

Define a string as:

<resources>
    <string name="your_string">This is an <u>underline</u> text demo for TextView.</string>
</resources>

Upvotes: 34

Harsh Dev Chandel
Harsh Dev Chandel

Reputation: 763

tobeunderlined= <u>some text here which is to be underlined</u> 

textView.setText(Html.fromHtml("some string"+tobeunderlined+"somestring"));

Upvotes: 3

josephus
josephus

Reputation: 8304

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);

Upvotes: 10

kameny
kameny

Reputation: 2370

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

textView.setText(Html.fromHtml("this is <u>underlined</u> text"));

Upvotes: 41

Related Questions