How to Change programmatically Edittext Cursor Color in android?

前端 未结 9 430
眼角桃花
眼角桃花 2020-12-08 14:23

In android we can change the cursor color via:

android:textCursorDrawable=\"@drawable/black_color_cursor\".

How can we do this dynamically?

9条回答
  •  旧巷少年郎
    2020-12-08 15:10

    Inspired from @Jared Rummler and @Oleg Barinov I have crafted solution which works on API 15 also -

    public static void setCursorColor(EditText editText, @ColorInt int color) {
        try {
            // Get the cursor resource id
            Field field = TextView.class.getDeclaredField("mCursorDrawableRes");
            field.setAccessible(true);
            int drawableResId = field.getInt(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};
    
            if (Build.VERSION.SDK_INT == 15) {
                // Get the editor
                Class drawableFieldClass = TextView.class;
                // Set the drawables
                field = drawableFieldClass.getDeclaredField("mCursorDrawable");
                field.setAccessible(true);
                field.set(editText, drawables);
    
            } else {
                // Get the editor
                field = TextView.class.getDeclaredField("mEditor");
                field.setAccessible(true);
                Object editor = field.get(editText);
                // Set the drawables
                field = editor.getClass().getDeclaredField("mCursorDrawable");
                field.setAccessible(true);
                field.set(editor, drawables);
            }
        } catch (Exception e) {
            Log.e(LOG_TAG, "-> ", e);
        }
    }
    

提交回复
热议问题