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
You should use activated state to enable or disable button . It is clickable or as someone point use selected or checked state. Each of these state has a different meaning so use it carefully
I'm about to tackle this by using the selected
state, which is generally available for use in widgets, and can be used in state list drawables. A simple search for usage of isSelected
turns up results in ListView, GridView, TextView and TabLayout. And the documentation states
Views are typically * selected in the context of an AdapterView like ListView or GridView; * the selected view is the view that is highlighted.
Instead of disabling it, keep it enabled but use a flag to control your "inner state"
I looked for it but got nothing to listen the EditText block. So I find another way to activate it. If there is a near button or area that you already listen, you can enable SetOnLongClickListener
to activate the block. It will be a secret but you can tell the users.
button.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
editText.setEnabled(true)
return true;
}
});
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
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()
}