在不使用反射的情况下,从代码中更改 TextInputEditText 光标的颜色。
我试过这个:
val fCursorDrawableRes = TextView::class.java.getDeclaredField("mCursorDrawableRes")
fCursorDrawableRes.isAccessible = true
val mCursorDrawableRes = fCursorDrawableRes.getInt(editText)
val fEditor = TextView::class.java.getDeclaredField("mEditor")
fEditor.isAccessible = true
val editor = fEditor.get(editText)
val clazz = editor.javaClass
val fCursorDrawable = clazz.getDeclaredField("mCursorDrawable")
fCursorDrawable.isAccessible = true
val drawables = arrayOfNulls<Drawable>(2)
drawables[0] = editText.context.resources.getDrawable(mCursorDrawableRes)
drawables[1] = editText.context.resources.getDrawable(mCursorDrawableRes)
drawables[0]!!.setColorFilter(color, PorterDuff.Mode.SRC_IN)
drawables[1]!!.setColorFilter(color, PorterDuff.Mode.SRC_IN)
fCursorDrawable.set(editor, drawables)
这适用于Android版本<9.0,对于版本9,他们@UnsupportedAppUsage用于mCursorDrawableRes,因此无法访问它。还有其他方法可以做到吗?
添加一个主题,其中光标可绘制为编辑文本:
<style name="myStyle" parent="@android:style/Widget.Holo.Light.EditText">
<item name="android:background">@android:drawable/editbox_background_normal</item>
<item name="android:textCursorDrawable">@android:drawable/my_cursor_drawable</item>
</style>