android - 在 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
但仍然没有效果。
有谁知道我做错了什么?
解决方案
经过进一步调查,我发现setTextCursorDrawable(@Nullable Drawable textCursorDrawable)
每个EditText
. 因此,如果您将 textCursorDrawable 更改为您的自定义一次,那么您将无法将其更改为另一个,它只会忽略您想要进行的任何更改。
我的屏幕具有默认状态,因此在屏幕初始化期间setTextCursorDrawable
第一次更改了可绘制的光标,但我没有注意到这一点。
因此请注意错误(或预期的行为可能?),您无法在每个EditText
.
推荐阅读
- bash - 自称 bash 深情的“引用中引用”问题
- pact - 契约测试 - 对象中具有多个键值对的 Json 请求正文,但键可以是任何东西
- python - 如何从python字典中的元组键中获取值
- mysql - 如果在蜘蛛关闭且原因完成时 process_item 没有完成会发生什么?
- javascript - 变量作为参数导致问题
- r - 在列上保留某种类型,在 R 中的列上只保留一种类型?
- docusignapi - DocuSign - 非管理员用户的“JWT Grant”?
- bash - 为什么这个算术运算在 GNU bash 中不起作用?
- java - 有没有办法在 Swing 的自定义绘制图表中间显示一个项目?
- java - BitmapFactory.decodeStream 导致:D/skia: --- 无法创建带有消息“未实现”的图像解码器