Search code examples
androidtextview

How to change the cursor color of textview when selecting text


I am trying to change the highlight color and the cursor color when selecting text in a text view. Through stackoverflow posts, I was able to change the highlight color using

textView.highlightColor = ContextCompat.getColor(context, R.color.red_1)

I wanted to change the cursor color to a custom color. By going through a lot of stackoverflow posts, one of the answers suggested to change the accent color. But I don't want to change that because it'll affect a lot of UI properties in my app. I couldn't find any other solution.

enter image description here


Solution

  • Changing the handle color with defining a @style through Theme:

    <style name="MyCustomTheme" parent="@style/MyNotSoCustomTheme">
            <item name="android:textSelectHandle">@drawable/text_select_handle_middle</item>
            <item name="android:textSelectHandleLeft">@drawable/text_select_handle_left</item>
            <item name="android:textSelectHandleRight">@drawable/text_select_handle_right</item>
    </style>
    

    For doing it programmatically:

    try {
        final Field fEditor = TextView.class.getDeclaredField("mEditor");
        fEditor.setAccessible(true);
        final Object editor = fEditor.get(editText);
    
        final Field fSelectHandleLeft = editor.getClass().getDeclaredField("mSelectHandleLeft");
        final Field fSelectHandleRight = editor.getClass().getDeclaredField("mSelectHandleRight");
        final Field fSelectHandleCenter = editor.getClass().getDeclaredField("mSelectHandleCenter");
    
        fSelectHandleLeft.setAccessible(true);
        fSelectHandleRight.setAccessible(true);
        fSelectHandleCenter.setAccessible(true);
    
        final Resources res = context.getResources();
    
        fSelectHandleLeft.set(editor, res.getDrawable(R.drawable.text_select_handle_left));
        fSelectHandleRight.set(editor, res.getDrawable(R.drawable.text_select_handle_right));
        fSelectHandleCenter.set(editor, res.getDrawable(R.drawable.text_select_handle_middle));
    } catch (final Exception ignored) {
    }
    

    For changing the selected text color you can set textColorHighlight in xml as:

    android:textColorHighlight="#ff0000"
    

    through style you can achieve that with:

    <item name="android:textColorHighlight">@color/m_highlight_green</item>