以编程方式更改光标颜色,而无需使用反射

时间:2019-01-11 05:48:35

标签: android android-textinputedittext

无需使用反射即可从代码中更改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,因此无法访问它。 还有其他方法吗?

1 个答案:

答案 0 :(得分:1)

使用可绘制光标为EditText添加主题:

<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>