问题描述
我想将自定义可绘制对象设置为EditText
的光标。
对于API
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所做的任何更改只有在光标被隐藏然后再次绘制后才可见。
所以我认为我需要手动隐藏光标并通过setCursorVisible
方法使其可见,但仍然没有效果。
有人知道我在做什么错吗?
解决方法
进一步调查后,我发现setTextCursorDrawable(@Nullable Drawable textCursorDrawable)
每个EditText
实例只能工作一次。因此,如果将textCursorDrawable更改为自定义一次,则无法将其更改为另一种,它将忽略您要进行的任何更改。
我的屏幕处于默认状态,因此在屏幕初始化期间setTextCursorDrawable
首次更改了可绘制的光标,但是我没有注意到。
因此请注意错误(或预期的行为?),您无法在一个EditText
的每个实例中多次更改可绘制游标。