Michael Allen
Michael Allen

Reputation: 5828

ListView item with a button on it swallows touch events

I'm working on an android app in which I'm displaying a list of items and allowing the user to click on a star icon to favourite items, which will then be displayed in a separate activity.

For this list then I am using a RelativeLayout with a ImageView for an icon, a TextView for a name of the item and an Button for the favourite button.

The problem I have is that without the button the list items touch properly and glow on response to a touch. With the button however they dont glow correctly, however they will fire any methods I place in the android:onClick xml attribute of the relativeLayout

Does anyone know of a way to fix this behaviour?

Upvotes: 5

Views: 5120

Answers (3)

Miracula
Miracula

Reputation: 81

When using an ImageButton you have to call

myImageButton.setFocusable(false);

programmatically because its constructor sets it to true. You can do so by overwriting the getView-method of your adapter:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View view = super.getView(position, convertView, parent);
    view.findViewById(R.id.idOfYourImageButton).setFocusable(false);
    return view;
}

Upvotes: 8

Steven Elliott
Steven Elliott

Reputation: 3224

There are a lot of stackoverflow questions on this, but none that seemed to give a simple solution, so I'm posting what worked for me here:

My specific example involves a ListFragment, each item in the listview contains a standard button. I want the button and the listview to be clickable separately.

In the listFragment, add this:

    @Override
    public void onActivityCreated (Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        this.getListView().setItemsCanFocus(false);
    }

In the xml for the row item, add this to the Button XML:

android:focusable="false"

.. and that's it. Did the trick for me.

Upvotes: 1

100rabh
100rabh

Reputation: 6186

Did you set listview focusable to be false

Here are some similar problems

Focusable EditText inside ListView

Using a checkbox with a false focusable, still prevents listview clicks

and some more here

Upvotes: 1

Related Questions