I know how to underline text in a textview. But how to underline text with some different color ? Underline can be done with:
TextView t = (TextView) findViewById(R.id.textview);
t.setPaintFlags(t.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
t.setText("Underline Text");
Let say my textcolor is black and I want to underline the same with blue color, how to do it ? Thanks in advance.
If you are an XML's fan. Take a look at my solution:
Create a selector
selector_edittext_white.xml
in drawable folderThen, set your EditText
In the setting above, the underline's color is white, and you can move it by changing
android:bottom
above is "-15dp" . In case it's disappear, try to set your EditText bottom margin like thisYou can try out as below:
make a new paint color. and assign the paint to the textview.
I had the same problem and I have stumbled upon Layout class when reading some other posts for doing this on
EditText
. It provides everything you need to make this happen by manually drawing underline with canvas.First I defined custom attributes for an easy customization in XML layout files
And a custom
TextView
classThen it's usage is simple
Final result
Another solution, this time without extending TextView (based on a question I wrote a long time ago, here) :
Have a drawable to be shown as the underline, and have a span for the text itself :
text_underline.xml
DrawableSpan.kt
usage:
And the result:
I can't add a comment yet, so I'm posting as an answer instead.
I just want to say that Bojan Kseneman's answer (https://stackoverflow.com/a/30717100/2771087) is fantastic. There's one issue with it that I'd like to correct, though.
Rather than finding the end position of the last character in a line, it's grabbing the end of second last character and then adding the width of the first character in the line. These two lines here:
Instead of this, getSecondaryHorizontal() can be used to grab the opposite side of the character, as in:
However, this will also underline the space at the end of each line for multi-line text areas. So to fix that issue, use code like the following to skip past it before calculating x_stop: