How to set color of UnderlineSpan?

2019-04-24 10:07发布

问题:

This question is a follow up to my last question: How to highlight text like Android spell-checker?

I'm using an UnderlineSpan to underline text in an EditText but I need the underline to be IN COLOR like this screen shot of the spelling checker:

回答1:

Unfortunately, you can't do this solely with a Span -- there are no public methods to do what you ask. There is a method to set the underline color in TextPaint independent of the text color (you can see it in the source code for SuggestionSpan) but it's hidden.

If you can get access to the EditText, you can handle the Span and draw the underline yourself, but otherwise you are out of luck.



回答2:

here is the function which you can use to set color of line below text

public void addUnderLineLink(TextView mTextView) {
    if (mTextView != null) {
        SpannableString content = new SpannableString(mTextView.getText().toString());
        UnderlineSpan us=new UnderlineSpan();
        TextPaint tp=new TextPaint();
        tp.setColor(ContextCompat.getColor(getContext(),R.color.white));
        us.updateDrawState(tp);
        content.setSpan(us, 0, mTextView.getText().toString().length(), 0);
        mTextView.setText(content);
    }
}


回答3:

This is how i made it work

Spanned part_1 = Html.fromHtml(getString(R.string.part1));
Spanned part_2 = Html.fromHtml("<u><font color='#2eb6f0'>Text in blue</font></u>");
Spanned part_3 = Html.fromHtml(getString(R.string.part3));
Spanned output = (Spanned) TextUtils.concat(part_1, part_2, part_3);

textview.setText(output, TextView.BufferType.SPANNABLE);