When should one use android:clickable?
As the documentation states, and as far as I know :
clickable
- Defines whether this view reacts to click events. Must be a boolean value, either "true" or "false".
So for example if you just declare a Webview
or View
in your layout.xml
and try to set an OnClickListener
on this views the OnClick
event won't be fired unless you specify the attribute :
android:clickable=true
clickable
seems to be useful when you need a view to consume clicks so that they do not go to views beneath the top view.
For example, I have a FrameLayout
that I display over an underlying RelativeLayout
at certain times. When the user would click on an underlying EditText
the focus would shift to that EditText
. Really annoying when the FrameLayout
was still being shown. Now the user doesn't know why a keyboard just popped up or where they are typing.
When I set clickable="true"
in the FrameLayout
, users could no longer accidentally click underlying EditText
fields.
<RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" ...> <EditText> <EditText> <EditText> <!-- FrameLayout with grayed-out background. --> <FrameLayout android:id="@+id/sometimes_visible_view" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#80808080" android:clickable="true" android:visibility="gone" android:focusable="true" ...> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" ...> <View> <View> </LinearLayout> </FrameLayout></RelativeLayout>
When you are setting view.setOnClickListener
on any View
,eg: myButton.setOnClickListener(new OnClickListener)
by default it is considered as clickable="true"
.
So you would not need to mention that in the XML file like android:clickable="true"
. The onClick()
event will be fired without usingandroid:clickable="true"
.