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

标签 java android reflection android-edittext textview

我一直在使用反射方法以编程方式设置我的 EditText 的光标颜色,这是我从 answer 中找到的(我也试过这个 answer )。但是,在最近的一些更新之后,记不清具体是什么时候,该方法不再有效,我认为 Android 可能已经更改了 TextView 类中的某些内容。无论如何,有人可以帮我吗? mCursorDrawableResmCursorDrawable 现在是否有新的字段名称,或者整个方法是否无效并且现在需要以其他方式实现?

更新:我刚刚发现此方法仅在 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/

相关文章:

java - 如何打破 for 循环相对于其他 for 循环的关系

java - 尝试编译 Cyber​​duck 和 ant 错误

Android:使用 SurfaceView 内容创建位图

java - 方法注释和默认访问级别的奇怪行为

vb.net - 仅反射(reflect) VB.NET 上派生类的子属性

java - 在 Tomcat 中隐藏应用程序信息

java - tomcat隔离webapps

android - ToggleButton Canvas 上绘制的文本和线条出现在屏幕上但不出现在屏幕截图上

android - 以编程方式显示和隐藏 Bottom Sheet

c# - 如何在程序集中查找所有出现的自定义属性?