Last active
June 9, 2020 04:14
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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) {} | |
} |
@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
@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