【问题标题】:setCompoundDrawables not displaying iconsetCompoundDrawables 不显示图标
【发布时间】:2021-08-14 04:44:48
【问题描述】:

目前, 我正在实现一个片段来更改用户密码。为此,用户必须确认他的密码。当两个密码匹配时,我想在 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,但它也不起作用。

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

【问题讨论】:

    标签: android-studio kotlin android-edittext drawable


    【解决方案1】:

    在设置新的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)
    
    

    【讨论】:

    • 非常感谢。现在一切正常。
    猜你喜欢
    • 2011-09-29
    • 2017-10-20
    • 1970-01-01
    • 2021-05-19
    • 2016-09-12
    • 2019-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多