Can underline words in TextView text

前端 未结 5 1544
野趣味
野趣味 2021-02-02 09:45

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 ?

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-02 10:31

    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

提交回复
热议问题