LinearLayout as custom button, OnClickListener never called
Posted
by
ohra
on Stack Overflow
See other posts from Stack Overflow
or by ohra
Published on 2012-09-02T08:41:25Z
Indexed on
2012/09/02
9:38 UTC
Read the original article
Hit count: 260
I've been using the common Android Button with both icon (drawableTop) and text. It works really poorly if you want to have a non-standard size button, so I decided to make a custom button with a LinearLayout having the following layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
style="@style/ButtonHoloDark"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:clickable="true"
android:focusable="true"
android:orientation="vertical" >
<ImageView
android:id="@+id/buttonIcon"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:duplicateParentState="true" />
<TextView
android:id="@+id/buttonText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:duplicateParentState="true"
android:gravity="center"
android:textColor="@color/white" />
</LinearLayout>
The layout is used by a custom class:
public class CustomIconButton extends LinearLayout {
public CustomIconButton(Context context, AttributeSet attrs) {
super(context, attrs);
setAttributes(context, attrs);
LayoutInflater.from(context).inflate(R.layout.custom_icon_button, this, true);
}
...
But when I set an OnClickListener on my button in its parent layout it never gets called. I can only receive clicks if a set the listener to the ImageView and/or TextView. This leads to two possible effects when the button is clicked:
- The click is inside the ImageView or the TextView. The click is registered ok, but the buttons state drawable doesn't change i.e. it doesn't appear depressed.
- The click is inside the "empty area" of the button. The click is not registered, but the state drawable works ok.
Neither of these is feasible. I've played around with the following attributes on the LinearLayout or its children, but none really seem to have any effect whether true or false:
- duplicateParentState
- clickable
- focusable
There doesn't seem to be any reasonable way to get the LinearLayout parent receive clicks instead of its children. I've seen some possible solutions overriding dispatchTouchEvent or onInterceptTouchEvent on the custom component itself, but that really seems like a big mess if I have to start analyzing touch events to identify proper clicks.
So OnClickListener on a LinearLayout with children = no go?
© Stack Overflow or respective owner