Set EditText cursor color

后端 未结 24 1376
醉话见心
醉话见心 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:32

    For anyone that needs to set the EditText cursor color dynamically, below you will find two ways to achieve this.


    First, create your cursor drawable:

    
    
    
        
    
        
    
    
    

    Set the cursor drawable resource id to the drawable you created (https://github.com/android/platform_frameworks_base/blob/kitkat-release/core/java/android/widget/TextView.java#L562-564">source)):

    try {
        Field f = TextView.class.getDeclaredField("mCursorDrawableRes");
        f.setAccessible(true);
        f.set(yourEditText, R.drawable.cursor);
    } catch (Exception ignored) {
    }
    

    To just change the color of the default cursor drawable, you can use the following method:

    public static void setCursorDrawableColor(EditText editText, int color) {
        try {
            Field fCursorDrawableRes = 
                TextView.class.getDeclaredField("mCursorDrawableRes");
            fCursorDrawableRes.setAccessible(true);
            int mCursorDrawableRes = fCursorDrawableRes.getInt(editText);
            Field fEditor = TextView.class.getDeclaredField("mEditor");
            fEditor.setAccessible(true);
            Object editor = fEditor.get(editText);
            Class clazz = editor.getClass();
            Field fCursorDrawable = clazz.getDeclaredField("mCursorDrawable");
            fCursorDrawable.setAccessible(true);
    
            Drawable[] drawables = new Drawable[2];
            Resources res = editText.getContext().getResources();
            drawables[0] = res.getDrawable(mCursorDrawableRes);
            drawables[1] = res.getDrawable(mCursorDrawableRes);
            drawables[0].setColorFilter(color, PorterDuff.Mode.SRC_IN);
            drawables[1].setColorFilter(color, PorterDuff.Mode.SRC_IN);
            fCursorDrawable.set(editor, drawables);
        } catch (final Throwable ignored) {
        }
    }
    

提交回复
热议问题