Android EditText 设置光标颜色

private fun EditText.setCursorColor(color: Int) {
    try {
        val field = TextView::class.java.getDeclaredField("mCursorDrawableRes")
        field.isAccessible = true
        val mCursorDrawableRes = field.getInt(this)
        val fEditor = TextView::class.java.getDeclaredField("mEditor")
        fEditor.isAccessible = true
        val editor = fEditor.get(this)
        val clazz = editor.javaClass
        val fCursorDrawable = clazz.getDeclaredField("mCursorDrawable")
        fCursorDrawable.isAccessible = true
        val drawables = arrayOfNulls(2)
        val cursorDrawable = ResourcesCompat.getDrawable(context.resources, mCursorDrawableRes, null)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            cursorDrawable?.colorFilter = BlendModeColorFilter(color, BlendMode.SRC_IN)
        } else {
            //29以上才能使用BlendModeColorFilter
            cursorDrawable?.setColorFilter(color, PorterDuff.Mode.SRC_IN)
        }
        drawables[0] = cursorDrawable
        drawables[1] = cursorDrawable
        fCursorDrawable.set(editor, drawables)
    } catch (e: Exception) {
        e.printStackTrace()
    }
}
fun EditText.setEditCursorColor(color: Int) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        this.textCursorDrawable = ResourceUtil.createShapeDrawable(width = 1.5f, height = 10f, radius = 16f, solidColor = color)
    } else {
        this.setCursorColor(color)
    }
}

你可能感兴趣的:(Android EditText 设置光标颜色)