Android - How to tap ListView item programmatically
Asked Answered
B

7

31

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

Birr answered 22/3, 2012 at 10:12 Comment(2)
performItemClick is supposed to work, there is probably something wrong with the way you use itMonophthong
@cool dev have a look at my new answerGaff
E
70
mList.performItemClick(
    mList.getAdapter().getView(mActivePosition, null, null),
    mActivePosition,
    mList.getAdapter().getItemId(mActivePosition));

Where mActivePosition is your click position!

Endosmosis answered 29/4, 2013 at 12:5 Comment(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 themMisgive
This won't create a view. mList.performItemClick(mList.getChildAt(mActivePosition), mActivePosition, mList.getAdapter().getItemId(mActivePosition));Menashem
@Arst, Thank you very much for a perfect solution.Ranket
M
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.

Moiramoirai answered 18/4, 2013 at 8:42 Comment(0)
J
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.

Joeyjoffre answered 13/8, 2013 at 7:33 Comment(0)
S
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.

Scraggy answered 22/3, 2012 at 10:27 Comment(2)
But how do you use Robotium to do this?Weatherbeaten
Ask robotium to tap the text inside the list item.Scraggy
R
1

The answer is

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

from the link

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

Registered answered 11/12, 2012 at 12:50 Comment(0)
N
0

This will work!!

 listview.performItemClick(listview.getChildAt(position),
                    position,
                    listview.getChildAt(position).getId());
Nsf answered 14/2, 2022 at 8:59 Comment(0)
M
-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
    }
});
Magnificat answered 22/3, 2012 at 10:23 Comment(1)
The question is "How to tap ListView item programmatically?" and not about getting list item click event.Householder

© 2022 - 2024 — McMap. All rights reserved.