Disable an ImageButton

后端 未结 7 1799
小蘑菇
小蘑菇 2020-12-14 01:51

This looks easy, but I\'m not able to disable an ImageButton. It continues to receive click events, and its appearance don\'t change like a standard Button woul

7条回答
  •  一整个雨季
    2020-12-14 02:08

    I managed to build a solution inspired by Oleg Vaskevich's answer, but without the need to pass drawable resource ID to setEnabled().

    Here is Kotlin code, inside of utility module:

    fun Drawable.deepCopy(): Drawable =
        constantState?.newDrawable()?.mutate() ?:
            throw RuntimeException("Called on null Drawable!")
    
    fun Drawable.toGrayscale(): Drawable =
            deepCopy().apply { setColorFilter(Color.GRAY, PorterDuff.Mode.SRC_IN) }
    
    fun ImageButton.setAndShowEnabled(enabled: Boolean) {
        if (enabled == isEnabled)
            return
    
        isEnabled = enabled
    
        if (enabled) {
            setImageDrawable(tag as Drawable)
        }
        else {
            if (tag == null)
                tag = drawable
    
            setImageDrawable(drawable.toGrayscale())
        }
    }
    

    It can be used like this:

    val button: ImageButton = findViewById(...)
    // ...
    button.setAndShowEnabled(false)
    
    // launch async operation
    GlobalScope.launch {
        // do work here
    
        // unblock button
        button.setAndShowEnabled(true)
    }
    

提交回复
热议问题