我一直在使用反射方法以编程方式设置我的 EditText
的光标颜色,这是我从 answer 中找到的(我也试过这个 answer )。但是,在最近的一些更新之后,记不清具体是什么时候,该方法不再有效,我认为 Android 可能已经更改了 TextView
类中的某些内容。无论如何,有人可以帮我吗? mCursorDrawableRes
和 mCursorDrawable
现在是否有新的字段名称,或者整个方法是否无效并且现在需要以其他方式实现?
更新:我刚刚发现此方法仅在 Android P 上停止工作,在以前的版本上,它仍然有效。
更新2:我自己解决了问题,如果你也卡住了,请检查答案。
最佳答案
好的,在深入研究 Android Pie 源代码后,我发现 Google 已将 mCursorDrawable
更改为 mDrawableForCursor
,并将其类型从两个元素更改 Drawable
数组为简单的Drawable
,所以我在原来反射方式的基础上做了一些改动,现在适用于Android P:
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) {}
}
旁注,我真的希望 Google 可以添加一个公共(public)方法,如 setCursorDrawable() 或类似的方法,那样会容易得多。
关于java - 使用反射方法设置EditText光标颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52564294/