1. 程式人生 > >EditText 游標顏色更改 tinting

EditText 游標顏色更改 tinting

public static void tintCursorDrawable(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);


       if (mCursorDrawableRes <= 0) {
           return;
       }


       Drawable cursorDrawable = editText.getContext().getResources().getDrawable(mCursorDrawableRes);
       if (cursorDrawable == null) {
           return;
       }


       Drawable tintDrawable  = tintDrawable(cursorDrawable, ColorStateList.valueOf(color));
       Drawable[] drawables = new Drawable[] {tintDrawable, tintDrawable};
       fCursorDrawable.set(editor, drawables);
   } catch (Throwable ignored) {
   }

}

public static Drawable tintDrawable(Drawable drawable, ColorStateList colors) {
    final Drawable wrappedDrawable = DrawableCompat.wrap(drawable);
    DrawableCompat.setTintList(wrappedDrawable, colors);
    return wrappedDrawable;
}