android 代码+xml 设置光标颜色

先说在Java代码设置:

1. 在此目录建立:src/drawable/cursor_color.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
    <solid android:color="#a8a8a8"/>
    <size android:width="1dp"/>
</shape>

2. 用反射获取TextView的变量:mCursorDrawableRes

try {
    Field f = TextView.class.getDeclaredField("mCursorDrawableRes");
    f.setAccessible(true);
    f.set(editText, R.drawable.cursor_color);
} catch (Exception ignored) {
}

这是一个封装了共有方法,同样也是在代码中设置光标颜色,你可以直接拿去使用:

/**
 * 代码设置光标颜色
 *
 * @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) {
    }
}

mxl设置光标颜色:

EditText有一个属性:android:textCursorDrawable,这个属性是用来控制光标颜色的
android:textCursorDrawable="@null","@null"作用是让光标颜色和text color一样

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值