我使用的是 Android API 28 x86 模拟器,我的项目目标/编译 SDK 版本是 28。考虑到这一点,我可以继续解决真正的问题。
我正在尝试使用反射在运行时更改 EditText 光标的颜色。查看SDK 28文件,我找到了我想要更改的字段的名称,它是“mDrawableForCursor”,该字段存在于Editor类内部。不知道为什么,这个类不能被我的项目引用,但这不是问题,我也可以通过反射得到它的引用。所以,我写了下面的代码
// Get the cursor resource id
Field field = TextView.class.getDeclaredField("mCursorDrawableRes");
field.setAccessible(true);
int drawableResId = field.getInt(this._inputEditText);
field.setAccessible(false);
// Get the editor
field = TextView.class.getDeclaredField("mEditor");
field.setAccessible(true);
Object editor = field.get(this._inputEditText);
field.setAccessible(false);
// Get the drawable and set a color filter
Drawable cursorPipe = ContextCompat.getDrawable(getContext(), drawableResId);
cursorPipe.setColorFilter(color, PorterDuff.Mode.SRC_IN);
Drawable[] drawables = {cursorPipe, cursorPipe};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
field = editor.getClass().getDeclaredField("mDrawableForCursor"); // error
} else {
field = editor.getClass().getDeclaredField("mCursorDrawable");
} …Run Code Online (Sandbox Code Playgroud)