Android - Listen to a disabled button

前端 未结 8 2160
一整个雨季
一整个雨季 2021-01-17 08:56

How can I respond to an event based on clicking a disabled Button. I have a requirement that I have to present Dialog, when a disabled Button

8条回答
  •  天命终不由人
    2021-01-17 09:17

    You can override onTouchEvent and create a listener like this :

    class MyButton @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = R.attr.materialButtonStyle) : MaterialButton(context, attrs, defStyleAttr) {
    
        private var onDisableClickListener: OnClickListener? = null
    
        override fun onTouchEvent(event: MotionEvent?): Boolean {
            if (event?.action == MotionEvent.ACTION_DOWN && !isEnabled) {
                onDisableOnClickListener?.onClick(this)
            }
            return super.onTouchEvent(event)
        }
    
        fun setOnDisableClickListener(l: OnClickListener?) {
            onDisableClickListener = l
        }
    }
    

    In your activity :

    button.setOnDisableClickListener {
                Toast.makeText(this), "The button is disabled", Toast.LENGTH_SHORT).show()
    }
    button.setOnClickListener {
                Toast.makeText(this), "The button is enabled", Toast.LENGTH_SHORT).show()
    }
    

提交回复
热议问题