tint Cursor Drawable - Android Graphics

Android examples for Graphics:Drawable Tint

Description

tint Cursor Drawable

Demo Code


import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.drawable.Drawable;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import java.lang.reflect.Field;

public class Main {
  public static void tintCursorDrawable(EditText editText, int color) {
    try {/*from www.  j a  va 2s .c  om*/
      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;
  }

  public static void tintDrawable(Context context, ImageView imageView, int colorResID) {
    Drawable originalDrawable = imageView.getDrawable();
    if (originalDrawable == null) {
      return;
    }
    imageView.setImageDrawable(
        tintDrawable(originalDrawable.mutate(), ColorStateList.valueOf(context.getResources().getColor(colorResID))));
  }
}

Related Tutorials