30

In android we can change the cursor color via:

android:textCursorDrawable="@drawable/black_color_cursor".

How can we do this dynamically?

In my case I have set cursor drawable to white, but i need to change black How to do ?

    // Set an EditText view to get user input
    final EditText input = new EditText(nyactivity);
    input.setTextColor(getResources().getColor(R.color.black));
Cœur
  • 37,241
  • 25
  • 195
  • 267
Amit Prajapati
  • 13,525
  • 8
  • 62
  • 84
  • follow [this link](https://stackoverflow.com/questions/7238450/set-edittext-cursor-color), the best to go for. – TankRaj Sep 10 '17 at 06:12

11 Answers11

87

Using some reflection did the trick for me

Java:

// https://github.com/android/platform_frameworks_base/blob/kitkat-release/core/java/android/widget/TextView.java#L562-564
Field f = TextView.class.getDeclaredField("mCursorDrawableRes");
f.setAccessible(true);
f.set(yourEditText, R.drawable.cursor);

XML:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <solid android:color="#ff000000" />

    <size android:width="1dp" />

</shape>

Here is a method that you can use that doesn't need an XML:

public static void setCursorColor(EditText view, @ColorInt int color) {
  try {
    // Get the cursor resource id
    Field field = TextView.class.getDeclaredField("mCursorDrawableRes");
    field.setAccessible(true);
    int drawableResId = field.getInt(view);

    // Get the editor
    field = TextView.class.getDeclaredField("mEditor");
    field.setAccessible(true);
    Object editor = field.get(view);

    // Get the drawable and set a color filter
    Drawable drawable = ContextCompat.getDrawable(view.getContext(), drawableResId);
    drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);
    Drawable[] drawables = {drawable, drawable};

    // Set the drawables
    field = editor.getClass().getDeclaredField("mCursorDrawable");
    field.setAccessible(true);
    field.set(editor, drawables);
  } catch (Exception ignored) {
  }
}
Jared Rummler
  • 37,824
  • 19
  • 133
  • 148
  • 1
    If anyone wants to change cursor pointer color. Use Jared Rummler approach but: instead of "mCursorDrawableRes" use "mTextSelectHandleRes" instead of "mCursorDrawable" use "mSelectHandleCenter" if you also need selection on top of that use mTextSelectHandleLeftRes, mTextSelectHandleRightRes and mSelectHandleLeft, mSelectHandleRight accordingly Checkout TextView.java and Edit.java for more information – Ivanov Maksim Mar 29 '18 at 12:24
  • 1
    Not working in API 15, java.lang.NoSuchFieldException: mEditor, Can you please provide some solution? – Hrishikesh Kadam Jul 25 '18 at 14:53
  • Has anyone tried to change the color of the caret on PIXEL XL phone updated to API 28? In my case the reflection cannot find the "mCursorDrawable" of the "mEditor". I found some posts online suggesting to use "mDrawableForCursor" instead, but the result is the same. Can anyone suggest approach which does not use any XML and works for all devices? – Pavel Pavlov Apr 09 '19 at 11:25
  • Also the first approach will change the caret for all instances of EditText in the application. How should one change the color only of a specific instance of EditText ? – Pavel Pavlov Apr 09 '19 at 11:47
  • it is showing me an error like "No field mCursorDrawable in class Landroid/widget/Editor; (declaration of 'android.widget.Editor' appears in /system/framework/framework.jar!classes2.dex)" – Pooja Shukla May 22 '19 at 06:21
  • 2
    @PavelPavlov since Android P, reflection `mDrawableForCursor` is in blacklist, use xml `android:textCursorDrawable` option if you still want to change cursor color. More info https://developer.android.com/distribute/best-practices/develop/restrictions-non-sdk-interfaces – cuasodayleo Jun 11 '19 at 09:18
  • @cuasodayleo the question I asked was to implement the same behavior entirely in Java (with no XML). Here is my original post (3 replies above): "Has anyone tried to change the color of the caret on PIXEL XL phone updated to API 28? In my case the reflection cannot find the "mCursorDrawable" of the "mEditor". I found some posts online suggesting to use "mDrawableForCursor" instead, but the result is the same. Can anyone suggest approach which does not use any XML and works for all devices?" – Pavel Pavlov Jun 12 '19 at 10:11
  • 1
    Let me clarify it again. The answer is you can't do it without XML. Since Android P they locking down on certain uses of reflection. It means even you can see `mDrawableForCursor` property in `Editor` but can't access it as we did with pre-P. This is from the official document and happens for all Android P devices not only PIXEL XL. – cuasodayleo Jun 12 '19 at 10:57
  • I get a warning " Reflective access to mCursorDrawableRes will throw an exception when targeting API 30 and above" – Simple UX Apps Jun 03 '22 at 18:00
17
android:textCursorDrawable="@null"

Then in the application:

final EditText input = new EditText(nyactivity);
input.setTextColor(getResources().getColor(R.color.black));

Get from here

Community
  • 1
  • 1
Orest Savchak
  • 4,529
  • 1
  • 18
  • 27
9

Kotlin version, works from api 14 to api 32

import android.content.Context
import android.content.res.ColorStateList
import android.graphics.drawable.Drawable
import android.graphics.drawable.GradientDrawable
import android.graphics.drawable.VectorDrawable
import android.os.Build
import android.util.TypedValue
import android.widget.TextView
import androidx.annotation.ColorInt
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.DrawableCompat
import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat
import java.lang.reflect.Field

fun TextView.setCursorDrawableColor(@ColorInt color: Int) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        textCursorDrawable = GradientDrawable(GradientDrawable.Orientation.BOTTOM_TOP, intArrayOf(color, color))
            .apply { setSize(2.spToPx(context).toInt(), textSize.toInt()) }
        return
    }

    try {
        val editorField = TextView::class.java.getFieldByName("mEditor")
        val editor = editorField?.get(this) ?: this
        val editorClass: Class<*> = if (editorField != null) editor.javaClass else TextView::class.java
        val cursorRes = TextView::class.java.getFieldByName("mCursorDrawableRes")?.get(this) as? Int ?: return

        val tintedCursorDrawable = ContextCompat.getDrawable(context, cursorRes)?.tinted(color) ?: return

        val cursorField = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            editorClass.getFieldByName("mDrawableForCursor")
        } else {
            null
        }
        if (cursorField != null) {
            cursorField.set(editor, tintedCursorDrawable)
        } else {
            editorClass.getFieldByName("mCursorDrawable", "mDrawableForCursor")
                ?.set(editor, arrayOf(tintedCursorDrawable, tintedCursorDrawable))
        }
    } catch (t: Throwable) {
        t.printStackTrace()
    }
}

fun Class<*>.getFieldByName(vararg name: String): Field? {
    name.forEach {
        try{
            return this.getDeclaredField(it).apply { isAccessible = true }
        } catch (t: Throwable) { }
    }
    return null
}

fun Drawable.tinted(@ColorInt color: Int): Drawable = when {
    this is VectorDrawableCompat -> {
        this.apply { setTintList(ColorStateList.valueOf(color)) }
    }
    Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && this is VectorDrawable -> {
        this.apply { setTintList(ColorStateList.valueOf(color)) }
    }
    else -> {
        DrawableCompat.wrap(this)
            .also { DrawableCompat.setTint(it, color) }
            .let { DrawableCompat.unwrap(it) }
    }
}

fun Number.spToPx(context: Context? = null): Float {
    val res = context?.resources ?: android.content.res.Resources.getSystem()
    return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, this.toFloat(), res.displayMetrics)
}
Niklas
  • 23,674
  • 33
  • 131
  • 170
John
  • 1,447
  • 15
  • 16
  • 2
    ... and after 8 years of Android development I spend hours to change the cursor color. I just want to cry. Thanks for your answer! – UneXp Dec 25 '19 at 18:00
  • 1
    @UneXp Changing handles color was harder though https://stackoverflow.com/a/59488928/1197590 – John Dec 26 '19 at 13:07
  • Working like a charm!! – Osvel Alvarez Jacomino May 17 '20 at 22:41
  • This works nice. Except for Huawei: `No field mDrawableForCursor in class Lhuawei/com/android/internal/widget/HwEditor; (declaration of 'huawei.com.android.internal.widget.HwEditor' appears in /system/framework/hwEmui.jar)`. @John, do you have solution there as well? – Niklas Mar 19 '22 at 12:41
  • 1
    @Niklas try edited code, it will probably work now – John Apr 07 '22 at 17:57
  • It does work on Huawei. – Niklas Apr 12 '22 at 21:20
  • @John do you also have a solution how to tint the dictionary suggestions when you type in a word that is incorrect? Here is an example: https://imgur.com/a/IXY4wNb - I want to change the color of the suggestions that are currently in green – Niklas May 09 '23 at 23:02
  • Decided to upstream it as it's own question since it's related but not the same: https://stackoverflow.com/questions/76213915/android-edittext-programmatically-tint-typo-dialog – Niklas May 09 '23 at 23:21
7

This is a rewritten version of the function from @Jared Rummler with a couple of improvements:

  • Support for Android 4.0.x
  • The special getDrawable(Context, int) function sience the getDrawable(int) is deprecated for API 22 and above.
private static final Field
        sEditorField,
        sCursorDrawableField,
        sCursorDrawableResourceField;

static {
    Field editorField = null;
    Field cursorDrawableField = null;
    Field cursorDrawableResourceField = null;
    boolean exceptionThrown = false;
    try {
        cursorDrawableResourceField = TextView.class.getDeclaredField("mCursorDrawableRes");
        cursorDrawableResourceField.setAccessible(true);
        final Class<?> drawableFieldClass;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
            drawableFieldClass = TextView.class;
        } else {
            editorField = TextView.class.getDeclaredField("mEditor");
            editorField.setAccessible(true);
            drawableFieldClass = editorField.getType();
        }
        cursorDrawableField = drawableFieldClass.getDeclaredField("mCursorDrawable");
        cursorDrawableField.setAccessible(true);
    } catch (Exception e) {
        exceptionThrown = true;
    }
    if (exceptionThrown) {
        sEditorField = null;
        sCursorDrawableField = null;
        sCursorDrawableResourceField = null;
    } else {
        sEditorField = editorField;
        sCursorDrawableField = cursorDrawableField;
        sCursorDrawableResourceField = cursorDrawableResourceField;
    }
}

public static void setCursorColor(EditText editText, int color) {
    if (sCursorDrawableField == null) {
        return;
    }
    try {
        final Drawable drawable = getDrawable(editText.getContext(), 
                sCursorDrawableResourceField.getInt(editText));
        drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);
        sCursorDrawableField.set(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN
                ? editText : sEditorField.get(editText), new Drawable[] {drawable, drawable});
    } catch (Exception ignored) {
    }
}

private static Drawable getDrawable(Context context, int id) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        return context.getResources().getDrawable(id);
    } else {
        return context.getDrawable(id);
    }
}
Oleg Barinov
  • 279
  • 5
  • 5
  • great, but i think it'd be better to replace your custom `getDrawable(context, resId)` method with `ContextCompat.getDrawable(context, resId)` - just the same method out of the box ;) – Alexander Krol May 03 '17 at 13:27
3

We managed to do it by:

  1. Creating a layout file with just an EditText and the cursor color set in xml on it.
  2. Inflating it
  3. Using the EditText as you would use a programmatically created one
Rotem
  • 2,306
  • 3
  • 26
  • 44
2

I wanted to build upon @John's answer. I found out that instead of using a GradientDrawable for Android >= Q you can just do:

textCursorDrawable?.tinted(color)

Therefore, the code becomes:

fun TextView.setCursorDrawableColor(@ColorInt color: Int) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        textCursorDrawable?.tinted(color)
        return
    }

    try {
        val editorField = TextView::class.java.getFieldByName("mEditor")
        val editor = editorField?.get(this) ?: this
        val editorClass: Class<*> = if (editorField != null) editor.javaClass else TextView::class.java
        val cursorRes = TextView::class.java.getFieldByName("mCursorDrawableRes")?.get(this) as? Int ?: return

        val tintedCursorDrawable = ContextCompat.getDrawable(context, cursorRes)?.tinted(color) ?: return

        val cursorField = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            editorClass.getFieldByName("mDrawableForCursor")
        } else {
            null
        }
        if (cursorField != null) {
            cursorField.set(editor, tintedCursorDrawable)
        } else {
            editorClass.getFieldByName("mCursorDrawable", "mDrawableForCursor")
                ?.set(editor, arrayOf(tintedCursorDrawable, tintedCursorDrawable))
        }
    } catch (t: Throwable) {
        t.printStackTrace()
    }
}

fun Class<*>.getFieldByName(vararg name: String): Field? {
    name.forEach {
        try{
            return this.getDeclaredField(it).apply { isAccessible = true }
        } catch (t: Throwable) { }
    }
    return null
}

fun Drawable.tinted(@ColorInt color: Int): Drawable = when {
    this is VectorDrawableCompat -> {
        this.apply { setTintList(ColorStateList.valueOf(color)) }
    }
    Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && this is VectorDrawable -> {
        this.apply { setTintList(ColorStateList.valueOf(color)) }
    }
    else -> {
        DrawableCompat.wrap(this)
            .also { DrawableCompat.setTint(it, color) }
            .let { DrawableCompat.unwrap(it) }
    }
}

fun Number.spToPx(context: Context? = null): Float {
    val res = context?.resources ?: android.content.res.Resources.getSystem()
    return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, this.toFloat(), res.displayMetrics)
}
Korax
  • 23
  • 3
1

Inspired from @Jared Rummler and @Oleg Barinov I have crafted solution which works on API 15 also -

public static void setCursorColor(EditText editText, @ColorInt int color) {
    try {
        // Get the cursor resource id
        Field field = TextView.class.getDeclaredField("mCursorDrawableRes");
        field.setAccessible(true);
        int drawableResId = field.getInt(editText);

        // Get the drawable and set a color filter
        Drawable drawable = ContextCompat.getDrawable(editText.getContext(), drawableResId);
        drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);
        Drawable[] drawables = {drawable, drawable};

        if (Build.VERSION.SDK_INT == 15) {
            // Get the editor
            Class<?> drawableFieldClass = TextView.class;
            // Set the drawables
            field = drawableFieldClass.getDeclaredField("mCursorDrawable");
            field.setAccessible(true);
            field.set(editText, drawables);

        } else {
            // Get the editor
            field = TextView.class.getDeclaredField("mEditor");
            field.setAccessible(true);
            Object editor = field.get(editText);
            // Set the drawables
            field = editor.getClass().getDeclaredField("mCursorDrawable");
            field.setAccessible(true);
            field.set(editor, drawables);
        }
    } catch (Exception e) {
        Log.e(LOG_TAG, "-> ", e);
    }
}
Hrishikesh Kadam
  • 35,376
  • 3
  • 26
  • 36
1
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        if (editText.getTextCursorDrawable() instanceof InsetDrawable) {
            InsetDrawable insetDrawable = (InsetDrawable) editText.getTextCursorDrawable();
            insetDrawable.setColorFilter(Color.BLUE, PorterDuff.Mode.SRC_ATOP);
            editText.setTextCursorDrawable(insetDrawable);
        }

        if (editText.getTextSelectHandle() instanceof BitmapDrawable) {
            BitmapDrawable insetDrawable = (BitmapDrawable) editText.getTextSelectHandle();
            insetDrawable.setColorFilter(Color.BLUE, PorterDuff.Mode.SRC_ATOP);
            editText.setTextSelectHandle(insetDrawable);
        }

        if (editText.getTextSelectHandleRight() instanceof BitmapDrawable) {
            BitmapDrawable insetDrawable = (BitmapDrawable) editText.getTextSelectHandleRight();
            insetDrawable.setColorFilter(Color.BLUE, PorterDuff.Mode.SRC_ATOP);
            editText.setTextSelectHandleRight(insetDrawable);
        }

        if (editText.getTextSelectHandleLeft() instanceof BitmapDrawable) {
            BitmapDrawable insetDrawable = (BitmapDrawable) editText.getTextSelectHandleLeft();
            insetDrawable.setColorFilter(Color.BLUE, PorterDuff.Mode.SRC_ATOP);
            editText.setTextSelectHandleLeft(insetDrawable);
        }
    }

Before Q (29) see: https://stackoverflow.com/a/44352565/2255331

maja89
  • 132
  • 1
  • 5
  • Can't you use editText.setTextCursorDrawable(ContextCompat.getDrawable(context, R.color.white)); directly ? As you are already wrapping for >= Android Q – Kishan Solanki Nov 22 '21 at 04:36
0

2019 Updated: working smooth and easy https://material.io/develop/android/docs/getting-started/

If you are using material component just simply use textCursorDrawable with color or your custom drawable.

    <com.google.android.material.textfield.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="12dp">

        <com.google.android.material.textfield.TextInputEditText
            android:layout_width="match_parent"
            android:textCursorDrawable="@color/red"
            android:cursorVisible="true"
            android:layout_height="wrap_content" />

    </com.google.android.material.textfield.TextInputLayout>
Amit Prajapati
  • 13,525
  • 8
  • 62
  • 84
0

Here is the solution for Xamarin based on John's answer

        public static void SetCursorDrawableColor(EditText editText, Color color)
        {
            try
            {
                if (Build.VERSION.SdkInt >= BuildVersionCodes.Q)
                {
                    var gradientDrawable = new GradientDrawable(GradientDrawable.Orientation.BottomTop, new[] { (int)color, color });
                    gradientDrawable.SetSize(SpToPx(2, editText.Context), (int)editText.TextSize);
                    editText.TextCursorDrawable = gradientDrawable;
                    return;
                }

                var fCursorDrawableRes =
                    Class.FromType(typeof(TextView)).GetDeclaredField("mCursorDrawableRes");
                fCursorDrawableRes.Accessible = true;
                int mCursorDrawableRes = fCursorDrawableRes.GetInt(editText);
                var fEditor = Class.FromType(typeof(TextView)).GetDeclaredField("mEditor");
                fEditor.Accessible = true;
                Java.Lang.Object editor = fEditor.Get(editText);
                Class clazz = editor.Class;

                if (Build.VERSION.SdkInt >= BuildVersionCodes.P)
                {
                    //TODO This solution no longer works in Android P because of reflection
                    // Get the drawable and set a color filter
                    Drawable drawable = ContextCompat.GetDrawable(editText.Context, mCursorDrawableRes);
                    drawable.SetColorFilter(color, PorterDuff.Mode.SrcIn);
                    var fCursorDrawable = clazz.GetDeclaredField("mDrawableForCursor");
                    fCursorDrawable.Accessible = true;
                    fCursorDrawable.Set(editor, drawable);
                }
                else
                {
                    Drawable[] drawables = new Drawable[2];
                    drawables[0] = ContextCompat.GetDrawable(editText.Context, mCursorDrawableRes).Mutate();
                    drawables[1] = ContextCompat.GetDrawable(editText.Context, mCursorDrawableRes).Mutate();
                    drawables[0].SetColorFilter(color, PorterDuff.Mode.SrcIn);
                    drawables[1].SetColorFilter(color, PorterDuff.Mode.SrcIn);

                    var fCursorDrawable = clazz.GetDeclaredField("mCursorDrawable");
                    fCursorDrawable.Accessible = true;
                    fCursorDrawable.Set(editor, drawables);
                }
            }
            catch (ReflectiveOperationException) { }
            catch (Exception ex)
            {
                Crashes.TrackError(ex);
            }
        }
        public static int SpToPx(float sp, Context context)
        {
            return (int)TypedValue.ApplyDimension(ComplexUnitType.Sp, sp, context.Resources.DisplayMetrics);
        }
0

You should change "colorAccent" and in order not to change this parameter for the whole application you can use ThemeOverlay. You can read more detailed in this article, the last section "Cursor and Selection"

Dharman
  • 30,962
  • 25
  • 85
  • 135