Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A reflection method used to set EditText Cursor Color with support for Android P (API 28)
public static void setEditTextCursorColor(EditText editText, int color) {
try {
// Get the cursor resource id
if(Build.VERSION.SDK_INT >= 28){//set differently in Android P and above (API 28+)
Field field = TextView.class.getDeclaredField("mCursorDrawableRes");
field.setAccessible(true);
int drawableResId = field.getInt(editText);
// Get the editor
field = TextView.class.getDeclaredField("mEditor");
field.setAccessible(true);
Object editor = field.get(editText);
// Get the drawable and set a color filter
Drawable drawable = ContextCompat.getDrawable(editText.getContext(), drawableResId);
drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);
// Set the drawables
field = editor.getClass().getDeclaredField("mDrawableForCursor");
field.setAccessible(true);
field.set(editor, drawable);
}else {
Field field = TextView.class.getDeclaredField("mCursorDrawableRes");
field.setAccessible(true);
int drawableResId = field.getInt(editText);
// Get the editor
field = TextView.class.getDeclaredField("mEditor");
field.setAccessible(true);
Object editor = field.get(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};
// Set the drawables
field = editor.getClass().getDeclaredField("mCursorDrawable");
field.setAccessible(true);
field.set(editor, drawables);
}
setEditTextHandleColor(editText, color);
} catch (Exception ignored) {
}
}
@PavelRPavlov

This comment has been minimized.

Copy link

commented Apr 9, 2019

This is a nice approach, but have you tried to deploy your application to PIXEL XL updated to latest API 28?
I have tried and the reflection does not seems to find the "mDrawableForCursor" field and throws exception. Have you found a way to approach this?

@thuypt

This comment has been minimized.

Copy link

commented Jun 11, 2019

@PavelRPavlov From Mike M commented, starting with P, Android locking down on certain uses of reflection, and mDrawableForCursor is in black list. Use xml to change Edittext cursor instead.
https://stackoverflow.com/questions/53304817/attribute-of-editor-class-cant-be-found-through-reflection

@jackz314

This comment has been minimized.

Copy link
Owner Author

commented Jun 11, 2019

@thuypt is right, this method is likely not going to survive long thanks to Google's crack down on reflections. The sad part is that there's still nothing publicly available to dynamically change certain attributes like the cursor color, I'll keep looking into it if anything works, but I highly doubt it unless Android makes some changes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.