Android问题汇总(遥远的回忆过去)

Android-EditText之代码动态修改编辑框光标颜色(通

2019-08-14  本文已影响1人  MonkeyLei

最近再做通用弹窗的封装FanChael/CommonPopupWindow,在涉及到注册、登录弹窗的时候,为了统一色调(光标、下划线、按钮),用户调用时会传入颜色“#xxxxxxx”,这个时候就需要修改:

1. 光标的颜色

2. 编辑框下划线的颜色(通过app模块下的style主题下增加control配色即可EditText下划线颜色修改 - 君子剑的博客 - CSDN博客

3. 按钮的颜色统一,由于用到了shape样式,所以就需要代码动态创建shape并进行按钮Button或者TextView的背景设置 MonkeyLei:Android-代码动态创建Shape并运用到控件背景(GradientDrawable)

所以就差光标颜色了,直接反射搞!

1. 工具类

EditTextUtil.java

import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.widget.EditText;
import android.widget.TextView;

import java.lang.reflect.Field;

/*
*@Description: 编辑框工具类
*@Author: hl
*@Time: 2019/2/20 9:29
*/
public class EditTextUtil {
    /**
     * 代码设置光标颜色
     *
     * @param editText 你使用的EditText
     * @param color    光标颜色
     */
    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);//SRC_IN 上下层都显示。下层居上显示。
            drawables[1].setColorFilter(color, PorterDuff.Mode.SRC_IN);
            fCursorDrawable.set(editor, drawables);
        } catch (Throwable ignored) {
        }
    }
}

2. 使用(TextInputEditText/EditText)

            ///< 编辑框下划线颜色、按钮颜色统一修改
            EditTextUtil.setCursorDrawableColor(usernameEt, Color.parseColor("#f0008DCF"));
            EditTextUtil.setCursorDrawableColor(verifypassEt, Color.parseColor("#f0008DCF"));

简单记录下,封装弹窗还是需要一些知识哒....小白的路还长....

上一篇下一篇

猜你喜欢

热点阅读