-1

Change the color of the Cursor of TextInputEditText from the code without using Reflection.

I have tried this:

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)

This works fine for Android version < 9.0, with the version 9 they have used @UnsupportedAppUsage for the mCursorDrawableRes, and hence not able to access it. Is there any other way to do it?

pixelWorld
  • 329
  • 2
  • 17

1 Answers1

1

Add a theme with your cursor drawable for the 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>
Maxim Firsoff
  • 2,038
  • 22
  • 28
  • Thanks for the reply, but is there a way to do this programmatically? I want to do change the color which is dependent on some logic in the code. – pixelWorld Jan 11 '19 at 18:45
  • Seems like it's not a trivial thing, try to replace the EditText with a new one and apply your theme for it (look at details here: https://gist.github.com/romannurik/7026222 ), better to create a custom EditText with a static factory to create a stylized instance. – Maxim Firsoff Jan 12 '19 at 06:52
  • but with this approach you have to create style. So my thing was I want to have this api say setCursorColor(color) to be exposed to the user then the above approach wont work right? – pixelWorld Jan 12 '19 at 18:28