1

I want to change the color of EditText Color and width programmatically for all Edit Text used in the project based on the app theme selected.
So I can't do this using XML and need a programatic solution.

So I want to create a custom function to set this

void setEditTextColorDrawable(int ClrVar)
{
    // Code Todo 
}

I tried all the methods suggested in
set textCursorDrawable programmatically

The issue is, getDeclaredField("mCursorDrawableRes") is not available above API22.
So how do I do this for all API even above 22

try {
    // 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);
} catch (Exception ignored)
{
    log.d("TAG", "This is depricated")
}

Output : "This is depricated"

Cœur
  • 37,241
  • 25
  • 195
  • 267
Sujay U N
  • 4,974
  • 11
  • 52
  • 88

1 Answers1

-2
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];
        drawables[0] = editText.getContext().getResources().getDrawable(mCursorDrawableRes);
        drawables[1] = editText.getContext().getResources().getDrawable(mCursorDrawableRes);
        drawables[0].setColorFilter(color, PorterDuff.Mode.SRC_IN);
        drawables[1].setColorFilter(color, PorterDuff.Mode.SRC_IN);
        fCursorDrawable.set(editor, drawables);
    } catch (Throwable ignored) {
        ignored.getMessage();
    }
}

if you want change droplet color, can use this code: https://gist.github.com/jaredrummler/2317620559d10ac39b8218a1152ec9d4

tcqq
  • 41
  • 8