Alireza
Alireza

Reputation: 31

Focusable Button in Listview

For a ListView with custom row layout like this:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">


    <Button
    android:layout_width="51dp"
    android:layout_height="43dp"
    android:id="@+id/btnBin"
    android:focusable="false"
    android:focusableInTouchMode="false"
    android:background="@drawable/ktape" />

    <TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
     android:textAppearance="?android:attr/textAppearanceLarge"
     android:text="Temporary"
    android:id="@+id/txtShowUsername"
    android:layout_gravity="center_horizontal"
    android:layout_weight="1"
    android:paddingTop="20dp"
    android:gravity="right"
       android:paddingRight="10dp" />
</LinearLayout>

the button should not be focusable to let the ListView's OnItemClickListener execute:

    android:focusable="false"
    android:focusableInTouchMode="false"

Why do I need to set the focusable to false? why a focusable button prevents OnItemClickListener.OnItemClick() to execute?

Upvotes: 0

Views: 601

Answers (2)

Bob
Bob

Reputation: 13865

When you touch something on the screen, the touch gesture is get by the root view of your layout. Then it passes the touch gesture to its child one by one until it is consumed. If the child is a clickable view, then it consumes the touch gesture and returns true. So that the touch gesture will not be passed to other Views. If the child is not a clickable View, then it just returns false, the touch gesture will be passed to next children.

Finally, if no child view consumes the touch gesture, it will be sent back to the parent itself. Now the parent can consume the touch gesture, if it has any.

Now in your case, ListView is parent and Button is the child. First, ListView passes the touch gesture to the button. Since button is a clickable View by default, it consumes the touch gesture, so the OnItemClickListener of ListView will not work. By explicitly setting focusable, focusableInTouchMode, clickable as false, the button becomes non clickable View. So the button wont consume the touch gesture, and the OnItemClickListener of ListView works.

Upvotes: 1

Dennis van Opstal
Dennis van Opstal

Reputation: 1338

Try adding this line:

android:clickable="false"

Upvotes: 0

Related Questions