API Q+ 忽略了 EditText 的可绘制自定义光标

Custom cursor drawable for EditText is ignored on API Q+

我想将自定义可绘制对象设置为 EditText 的光标。

对于 API < Android 问:我正在使用反射,它按预期工作。从 Android Q 开始,我们有方便的方法 setTextCursorDrawable(@Nullable Drawable textCursorDrawable)。我像下面这样使用它:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
   textCursorDrawable = ContextCompat.getDrawable(context,R.drawable.drawable_cursor)!!.tintDrawable(color)
}

其中tintDrawable方法是:

private fun Drawable.tintDrawable(@ColorInt color: Int): Drawable {
   return when (this) {
      is VectorDrawableCompat -> this.apply { setTintList(ColorStateList.valueOf(color)) }
      is VectorDrawable -> this.apply { setTintList(ColorStateList.valueOf(color)) }
      else -> {
         val wrappedDrawable = DrawableCompat.wrap(this)
         DrawableCompat.setTint(wrappedDrawable, color)
         DrawableCompat.unwrap(wrappedDrawable)
      }
   }
}

R.drawable.drawable_cursor只是简单的矩形:

<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <size android:width="2dp" />
    <solid android:color="?android:textColorPrimary"  />
</shape>

但是根本看不到任何效果。即使不应用着色光标可绘制也保持不变。

文档中提到

Note that any change applied to the cursor Drawable will not be visible until the cursor is hidden and then drawn again.

所以我想我需要手动隐藏光标并通过setCursorVisible方法使其可见但仍然没有效果。

有人知道我做错了什么吗?

经过进一步调查,我发现 setTextCursorDrawable(@Nullable Drawable textCursorDrawable) 在每个 EditText 实例中只工作一次。因此,如果您将 textCursorDrawable 更改为自定义的一次,那么您将无法将其更改为另一个,它只会忽略您想要进行的任何更改。

我的屏幕有默认状态,所以在屏幕初始化期间 setTextCursorDrawable 第一次更改了可绘制的光标,但我没有注意到。

所以请注意错误(或可能是预期的行为?),您不能为每个 EditText.

实例多次更改可绘制光标