For anyone that needs to set the EditText cursor color dynamically, below you will find two ways to achieve this.
First, create your cursor drawable:
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>
Set the cursor drawable resource id to the drawable you created (source)):
java
try {
Field f = TextView.class.getDeclaredField("mCursorDrawableRes");
f.setAccessible(true);
f.set(yourEditText, R.drawable.cursor);
} catch (Exception ignored) {
}
To just change the color of the default cursor drawable, you can use the following method:
java
public static void setTextCursorColor(TextView textView, @ColorInt int color) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
final Drawable drawable = textView.getTextCursorDrawable();
drawable.setTint(color);
textView.setTextCursorDrawable(drawable);
} else try {
Field fCursorDrawableRes = TextView.class.getDeclaredField("mCursorDrawableRes");
fCursorDrawableRes.setAccessible(true);
int mCursorDrawableRes = fCursorDrawableRes.getInt(textView);
Field fEditor = TextView.class.getDeclaredField("mEditor");
fEditor.setAccessible(true);
Object editor = fEditor.get(textView);
Class<?> clazz = editor.getClass();
Field fCursorDrawable = clazz.getDeclaredField("mCursorDrawable");
fCursorDrawable.setAccessible(true);
Drawable[] drawables = new Drawable[2];
Resources res = textView.getContext().getResources();
drawables[0] = res.getDrawable(mCursorDrawableRes);
drawables[1] = res.getDrawable(mCursorDrawableRes);
drawables[0].setColorFilter(color, PorterDuff.Mode.SRC_IN);
drawables[1].setColorFilter(color, PorterDuff.Mode.SRC_IN);
fCursorDrawable.set(editor, drawables);
} catch (final Throwable throwable) {
if (DEBUG) throw new RuntimeException("can't set text cursor color", throwable);
}
}