Cursor not showing with BackgroundColorSpan

I use BackgroundColorSpan

to highlight certain text inside EditText

. The problem I am facing is that the textbox cursor is not visible if the color is 100% alpha and it is very difficult to see from lower alpha.

I did some digging through the code EditText

and Editor

(used to paint the text in EditText

) and I found that internally the Editor.onDraw(...)

cursor is colored before the layout (which in turn is the text paint):

    if (highlight != null && selectionStart == selectionEnd && mCursorCount > 0) {
>>      drawCursor(canvas, cursorOffsetVertical);
        // Rely on the drawable entirely, do not draw the cursor line.
        // Has to be done after the IMM related code above which relies on the highlight.
        highlight = null;

    if (mTextView.canHaveDisplayList() && canvas.isHardwareAccelerated()) {
        drawHardwareAccelerated(canvas, layout, highlight, highlightPaint,
    } else {
>>      layout.draw(canvas, highlight, highlightPaint, cursorOffsetVertical);


Does anyone know how I can reverse this behavior? The only options I can think of right now are to either draw a cursor or do some kind of reflection in voodoo. Both seem a bit crowded.


I've created a bug report for this tracker on Android:


source to share

1 answer

As a result, I decided to create two extensions. One from EditText and another one from BackgroundColorSpan


The extension BackgroundColorSpan

just doesn't change the background color TextPaint

in updateDrawState()

, but allows external classes to access that color.

The EditText extension looks for a custom BackgroundColorSpan

and manually draws the background inside onDraw()

before calling the super implementation.

This option shows the complete solution (Import needs to be created):

Note. This does not work very well if the range is preserved and restored (for example, when rotating), so it may be necessary to manipulate the gaps when recovering.



All Articles