首页 > 解决方案 > 在 API Q+ 上,EditText 的自定义光标可绘制被忽略

问题描述

我想将自定义可绘制对象设置为EditText.

对于 API < Android Q,我正在使用反射,它按预期工作。从 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>

但是根本没有明显的效果。即使没有应用着色光标drawable也保持不变。

文档中提到

请注意,应用于光标 Drawable 的任何更改将不可见,直到光标被隐藏然后再次绘制。

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

有谁知道我做错了什么?

标签: androidandroid-edittextandroid-view

解决方案


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

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

因此请注意错误(或预期的行为可能?),您无法在每个EditText.


推荐阅读