先说在Java代码设置:
1. 在此目录建立:src/drawable/cursor_color.xml
<?xml version="1.0"encoding="utf-8"?><shapexmlns:android="http://schemas.android.com/apk/res/android"android:shape="rectangle"><solidandroid:color="#a8a8a8"/><sizeandroid: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) { }这是一个封装了共有方法,同样也是在代码中设置光标颜色,你可以直接拿去使用:
/***代码设置光标颜色**@parameditText你使用的EditText*@paramcolor光标颜色*/public static voidsetCursorDrawableColor(EditText editText, intcolor) {try{ Field fCursorDrawableRes = TextView.class.getDeclaredField("mCursorDrawableRes");//获取这个字段fCursorDrawableRes.setAccessible(true);//代表这个字段、方法等等可以被访问intmCursorDrawableRes = 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 =newDrawable[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一样