Skip to content

Instantly share code, notes, and snippets.

@jackz314
Last active June 9, 2020 04:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jackz314/c938da733d5606a231dfbc850079f2cc to your computer and use it in GitHub Desktop.
Save jackz314/c938da733d5606a231dfbc850079f2cc to your computer and use it in GitHub Desktop.
A reflection method used to set EditText Cursor Color with support for Android P (API 28)
//StackOverflow solution by me here: https://stackoverflow.com/a/52564925/8170714
public static void setEditTextCursorColor(EditText editText, int color) {
try {
// Get the cursor resource id
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
if(Build.VERSION.SDK_INT >= 28){//set differently in Android P (API 28)
field = editor.getClass().getDeclaredField("mDrawableForCursor");
field.setAccessible(true);
field.set(editor, drawable);
}else {
Drawable[] drawables = {drawable, drawable};
field = editor.getClass().getDeclaredField("mCursorDrawable");
field.setAccessible(true);
field.set(editor, drawables);
}
//optionally set the "selection handle" color too
setEditTextHandleColor(editText, color);
} catch (Exception ignored) {}
}
@PavelRPavlov
Copy link

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
Copy link

thuypt 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
Copy link
Author

jackz314 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