How to Change programmatically Edittext Cursor Color in android?

前端 未结 9 442
眼角桃花
眼角桃花 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

    Using some reflection did the trick for me

    Java:

    // https://github.com/android/platform_frameworks_base/blob/kitkat-release/core/java/android/widget/TextView.java#L562-564
    Field f = TextView.class.getDeclaredField("mCursorDrawableRes");
    f.setAccessible(true);
    f.set(yourEditText, R.drawable.cursor);
    

    XML:

    
    
    
        
    
        
    
    
    

    Here is a method that you can use that doesn't need an XML:

    public static void setCursorColor(EditText view, @ColorInt int color) {
      try {
        // Get the cursor resource id
        Field field = TextView.class.getDeclaredField("mCursorDrawableRes");
        field.setAccessible(true);
        int drawableResId = field.getInt(view);
    
        // Get the editor
        field = TextView.class.getDeclaredField("mEditor");
        field.setAccessible(true);
        Object editor = field.get(view);
    
        // Get the drawable and set a color filter
        Drawable drawable = ContextCompat.getDrawable(view.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);
      } catch (Exception ignored) {
      }
    }
    

提交回复
热议问题