使用反射方法设置EditText光标颜色

jac*_*314 1 java reflection android textview android-edittext

我一直在使用反射方法以EditText编程方式设置我的光标颜色,这是我从此答案中找到的(我也尝试过此答案)。但是,在进行了一些最近的更新后,不记得确切的时间了,该方法不再起作用,我认为Android可能已经更改了TextView该类中的某些内容。无论如何,有人可以帮我吗?现在是否存在mCursorDrawableRes和的新字段名mCursorDrawable,或者整个方法是否无效并且需要以其他方式实现?

更新:我刚刚发现此方法仅在Android P上停止工作,在以前的版本上仍然有效。

更新2:我自己解决了问题,请检查答案是否也卡住了。

jac*_*314 5

好的,在深入研究Android Pie源代码之后,我发现Google已更改mCursorDrawablemDrawableForCursor,并将其类型也从两个元素Drawable数组Drawable更改为simple ,因此我在原始反射方法的基础上进行了一些更改,现在它适用于Android P:

 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 (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) {
    }
}
Run Code Online (Sandbox Code Playgroud)

旁注,我真的希望Google可以添加诸如setCursorDrawable()之类的公共方法或类似的方法,这样会容易得多。