Until now, when I wanted to stop the user from pressing the button, I would set the
button.setClickable(false);
and usually change the text to some kind of grey colour (to let the user know that the button is disabled). Today I stumbled upon the setEnabled()
property.
So I went to the documentation to see the method's explanation below:
setEnabled(boolean enabled)
Set the enabled state of this view.
What does this even mean? What is the difference between enable state/clickable state and disabled state/not clickable state? Could someone please explain what is the difference between doing what I was doing previously, using the clickable property and using the setEnabled()
property? What should be used when? I searched StackOverflow but could not find anything related. Thanks in advance.
Views can also respond to external keyboards, directional pads (remote/gaming controllers), and assistive devices (switch, screen readers).
As Dilip said, setClickable does not works if set at runtime. Here is a trick to make it working:
Quoting the Wikipedia page for "GUI widget":
This concept has been around for a couple of decades and can be found in most GUI frameworks.
In Android, a widget that is not clickable will not respond to click events. A disabled widget not only is not clickable, but it also visually indicates that it is disabled.
What makes a
Button
look and respond like aButton
is its background, which is aStateListDrawable
. There is a specific image used for the disabled state.So basically an enabled false doesn't respond to any response and an clickable false still response when set at runtime and trust me I just tried it.
The differences is listed above, but there is a tip. use setClickable() after setOnClickListener(). Because of this:
setClickable public void setClickable (boolean clickable)
It enables or disables click events for the particular view. When a view is clickable it will change its state to "pressed" on every click. if this property of view is disabled then it will not change its state.
setEnabled public void setEnabled (boolean enabled)
It set the enabled state of this view .If the particular view is set to be enabled then pass true in the parameter else pass false