Android EditText动态改变颜色

直接上代码

import android.content.Context
import android.content.res.ColorStateList
import android.graphics.drawable.Drawable
import android.os.Build
import android.util.AttributeSet
import android.widget.EditText
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.DrawableCompat
import com.google.android.material.textfield.TextInputEditText
import org.joor.Reflect

class ColorfulEditText : TextInputEditText {
    constructor(context: Context) : super(context)

    constructor(context: Context, attributeSet: AttributeSet) : super(context, attributeSet)

    constructor(context: Context, attributeSet: AttributeSet, defStyleAttr: Int) : super(
        context,
        attributeSet,
        defStyleAttr
    )

    fun applyColor(color: Int): ColorfulEditText {
        backgroundTintList = ColorStateList.valueOf(color)
        customCursorColor(color)
        return this
    }
}

fun EditText.customCursorColor(color: Int) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        textCursorDrawable = textCursorDrawable?.apply {
            setTint(color)
        }
        textSelectHandle?.apply {
            setTextSelectHandle(this.apply {
                setTint(color)
            })
        }
    } else {
        try {
            val editor = Reflect.on(this).get("mEditor")
            val mCursorDrawableRes = Reflect.on(this).get("mCursorDrawableRes")
            val drawable = ContextCompat.getDrawable(context, mCursorDrawableRes) ?: return
            val tintDrawable = DrawableCompat.wrap(drawable).apply {
                setTint(color)
            }
            if (Build.VERSION.SDK_INT == 28) {
                //此版本的具体实现跟其他的不一样
                //直接改drawable的颜色不知道为啥不行
                Reflect.on(editor).set("mDrawableForCursor", tintDrawable)
            } else {
                //此字段为final,只能替换里面的值
                val drawables = Reflect.on(editor).get>("mCursorDrawable")
                drawables[0] = tintDrawable
                drawables[1] = tintDrawable
            }

            val dotDrawableRes = Reflect.on(this).get("mTextSelectHandleRes")?:return
            val dotDrawable = ContextCompat.getDrawable(context, dotDrawableRes) ?: return
            val newDotDrawable = DrawableCompat.wrap(dotDrawable).apply {
                setTint(color)
            }
            Reflect.on(editor).set("mSelectHandleCenter", newDotDrawable)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}

你可能感兴趣的:(Android EditText动态改变颜色)