【问题标题】:Android Set textcursordrawable programmatically without reflection methodAndroid以编程方式设置textcursordrawable,无需反射方法
【发布时间】:2017-08-18 23:20:23
【问题描述】:

我想根据所选的应用主题以编程方式更改项目中使用的所有编辑文本的颜色和宽度。
所以我不能使用 XML 来做到这一点,需要一个编程解决方案。

所以我想创建一个自定义函数来设置这个

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

我尝试了
set textCursorDrawable programmatically

中建议的所有方法

问题是,getDeclaredField("mCursorDrawableRes") 在 API22 之上不可用。
那么我该如何为所有超过 22 的 API 执行此操作

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")
}

输出:“这是贬义的”

【问题讨论】:

    标签: java android android-edittext cursor


    【解决方案1】:
    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();
        }
    }
    

    如果你想改变水滴颜色,可以使用这个代码: https://gist.github.com/jaredrummler/2317620559d10ac39b8218a1152ec9d4

    【讨论】:

      猜你喜欢
      • 2012-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-15
      • 2016-11-10
      • 1970-01-01
      • 2015-06-24
      • 1970-01-01
      相关资源
      最近更新 更多