Android - Listen to a disabled button
A disabled button cannot listen to any event, but you can customize your own button by extending Button
class to make your own definition of disabling
Instead of disabling it, keep it enabled but use a flag to control your "inner state"
You can for example use #setActivated()
method instead. Disabling a view will ignore all events.
https://developer.android.com/reference/android/view/View.html#setActivated(boolean).
Then you can customize text and background styles with android:state_activate
attribute if you need:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_activated="false"
android:color="@color/a_color" />
<item android:state_activated="true"
android:color="@color/another_color" />
</selector>
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 (!isEnabled && event?.action == MotionEvent.ACTION_DOWN) {
onDisableClickListener?.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()
}