Adding a imagebutton to the layout of a custom item in a ListView stops receiving the long pressed event

StackOverflow https://stackoverflow.com/questions/13900662

Question

I'm making a listview with custom adapter / custom item layout (2x TextViews and 4x ImageButtons) and i want to be able to long press the list item to do something and still be able to press the ImageButtons on the layout.

The problem is that if i just have TextViews it works and catches the Long press event, as soon as i add an ImageButton the Long press event stops working. Any idea why this is happening?

Était-ce utile?

La solution

When you add clickable views (like buttons) in your item layout they catch the click event and it doesn't bubble to the underlying ListView, to fix this you can add the long click listener to the items' root layout.

So instead of doing this in your activity:

ListView lv = (ListView) findViewById(R.id.lv);
lv.setOnItemLongClickListener(listener);

you do this in your adapter:

@Override
public View getView(int position, View view, ViewGroup parent) {
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    view = inflater.inflate(R.layout.item, parent, false);

    view.setLongClickable(true);
    view.setOnLongClickListener(listener);
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top