setCompoundDrawables 不显示图标

setCompoundDrawables not displaying icon

目前, 我正在实现一个片段来更改用户密码。为此,用户必须确认他的密码。当两个密码都匹配时,我想在 EditText 中显示一个图标。为了在用户输入时验证这一点,我实现了以下功能:

 private fun EditText.afterTextChanged(afterTextChanged: (String) -> Unit) {
    this.addTextChangedListener(object : TextWatcher {
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        }

        override fun afterTextChanged(editable: Editable?) {
            afterTextChanged.invoke(editable.toString())
        }
    })
}

这样做我可以使用 editText.afterTextChanged{...} 来比较两个 editTexts 的值。当两个值匹配时,我目前正在尝试使用以下代码显示图标:

val icon = ResourcesCompat.getDrawable(
        resources,
        R.drawable.ic_baseline_check_circle_24,
        null
    )

    icon?.setBounds(
        0, 0,
        icon.intrinsicWidth,
        icon.intrinsicHeight
    )
    editText.setCompoundDrawablesWithIntrinsicBounds(null, null, icon, null)

不幸的是,这不起作用。我已经尝试使用 setCompoundDrawables 而不是 setCompoundDrawablesWithIntrinsicBounds 但这没有区别。此外,我尝试在函数中直接使用 R.drawable.ic_baseline_check_circle_24,但它也不起作用。

有人知道我的实施有什么问题吗?

设置新的Drawable前需要覆盖掉之前的Drawable

Android文档对该功能的描述如下:

Sets the Drawables (if any) to appear to the left of, above, to the right of, and below the text. Use null if you do not want a Drawable there. The Drawables' bounds will be set to their intrinsic bounds.

Calling this method will overwrite any Drawables previously set using setCompoundDrawablesRelative(Drawable, Drawable, Drawable, Drawable) or related methods.

所以需要先将Drawable设置为null,然后再试。

val icon = ResourcesCompat.getDrawable(
        resources,
        R.drawable.ic_baseline_check_circle_24,
        null
    )

    icon?.setBounds(
        0, 0,
        icon.intrinsicWidth,
        icon.intrinsicHeight
    )
    editText.setCompoundDrawables(null, null, null, null) //add this line code
    editText.setCompoundDrawablesWithIntrinsicBounds(null, null, icon, null)