Set EditText cursor color

后端 未结 24 1660
醉话见心
醉话见心 2020-11-22 10:57

I am having this issue where I am using the Android\'s Holo theme on a tablet project. However, I have a fragment on screen which has a white background. I am adding an

24条回答
  •  误落风尘
    2020-11-22 11:28

    Here @Jared Rummler's programatic setCursorDrawableColor() version adapted to work also on Android 9 Pie.

    @SuppressWarnings({"JavaReflectionMemberAccess", "deprecation"})
    public static void setCursorDrawableColor(EditText editText, int color) {
    
        try {
            Field cursorDrawableResField = TextView.class.getDeclaredField("mCursorDrawableRes");
            cursorDrawableResField.setAccessible(true);
            int cursorDrawableRes = cursorDrawableResField.getInt(editText);
            Field editorField = TextView.class.getDeclaredField("mEditor");
            editorField.setAccessible(true);
            Object editor = editorField.get(editText);
            Class clazz = editor.getClass();
            Resources res = editText.getContext().getResources();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                Field drawableForCursorField = clazz.getDeclaredField("mDrawableForCursor");
                drawableForCursorField.setAccessible(true);
                Drawable drawable = res.getDrawable(cursorDrawableRes);
                drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);
                drawableForCursorField.set(editor, drawable);
            } else {
                Field cursorDrawableField = clazz.getDeclaredField("mCursorDrawable");
                cursorDrawableField.setAccessible(true);
                Drawable[] drawables = new Drawable[2];
                drawables[0] = res.getDrawable(cursorDrawableRes);
                drawables[1] = res.getDrawable(cursorDrawableRes);
                drawables[0].setColorFilter(color, PorterDuff.Mode.SRC_IN);
                drawables[1].setColorFilter(color, PorterDuff.Mode.SRC_IN);
                cursorDrawableField.set(editor, drawables);
            }
        } catch (Throwable t) {
            Log.w(TAG, t);
        }
    }
    

提交回复
热议问题