31

How to call ItemClickListener programmatically? listView.performItemClick() does not work. Is that possible?

Alex Lockwood
  • 83,063
  • 39
  • 206
  • 250
Sandun Jay
  • 502
  • 2
  • 7
  • 23

7 Answers7

70
mList.performItemClick(
    mList.getAdapter().getView(mActivePosition, null, null),
    mActivePosition,
    mList.getAdapter().getItemId(mActivePosition));

Where mActivePosition is your click position!

Assaf Gamliel
  • 11,935
  • 5
  • 41
  • 56
Arun Jose
  • 1,857
  • 1
  • 15
  • 24
  • 3
    this will actually create a new view just so performItemClick will work, yes it will work, but this will not be the same view as intended, getView in adapter is misleading, it actually creates a view, and listView is using it in order to populate the views and recycle them – ndori Mar 23 '15 at 16:16
  • 7
    This won't create a view. `mList.performItemClick(mList.getChildAt(mActivePosition), mActivePosition, mList.getAdapter().getItemId(mActivePosition));` – Arst Mar 05 '18 at 11:03
  • @Arst, Thank you very much for a perfect solution. – Anirban Apr 01 '21 at 05:44
14

If you want to click/tap/select 3rd list item then.

listView.performItemClick(listView.getAdapter().getView(3, null, null), 3, listView.getItemIdAtPosition(3));

This worked perfectly for me.

Swapnil Godambe
  • 2,054
  • 1
  • 24
  • 29
4

Assign tag in the adapter to each View, and findviewByTag() this worked for me:

listView.performItemClick(listView.findViewWithTag(listView.getAdapter().getItem(selectedIndex)), selectedIndex, listView.getAdapter().getItemId(selectedIndex));

Also refer this answer.

Community
  • 1
  • 1
user1702512
  • 95
  • 1
  • 6
2

If you need it for testing purposes, then you can use Robotium ( http://code.google.com/p/robotium/ ).

You could also achieve what you want by calling the onClick method of the ClickController with the correct parameters.

Alex Lockwood
  • 83,063
  • 39
  • 206
  • 250
1

The answer is

listView1.performItemClick(listView1, 3, listView1.getItemIdAtPosition(3));

from the link

http://mantascode.com/?p=486

Abu Saad Papa
  • 1,908
  • 15
  • 20
0

This will work!!

 listview.performItemClick(listview.getChildAt(position),
                    position,
                    listview.getChildAt(position).getId());
-6

You can set up an onItemClick listener for your list view via

listView.setOnClickListener(new OnClickListener() {
    @Override
    public void   onClick(View v) {
        //here you do something
    }
});
Alex Lockwood
  • 83,063
  • 39
  • 206
  • 250
Artemis
  • 4,821
  • 3
  • 21
  • 24
  • 5
    The question is "How to tap ListView item programmatically?" and not about getting list item click event. – Zeba Feb 24 '14 at 14:29