Android app development: click a ListView item programmatically


I’m going to share a code snippet that you may use to programmatically click a ListView item in your Android app. This will not simply highlight the desired ListView item, but also trigger the onItemClick listener.

This code is what I placed in a Fragment’s onLoadFinished() method:

int default_position = 2;
listView.performItemClick(listView.getChildAt(default_position), default_position, listView.getItemIdAtPosition(default_position));


Simply replace the default_position value with the index number of the ListView item you want to click/select programmatically.

That item should be highlighted (assuming you have like, touch selectors) and also trigger the onItemClick listener on Android.


A possible error is . If this happens, wrap your code around a Runnable(), like this:

listView.post(new Runnable() {
    @Override
    public void run() {
        listView.performItemClick(listView.getChildAt(0), 0, listView.getItemIdAtPosition(0));
    }
});

Related Posts:

Posts that may be related to "Android app development: click a ListView item programmatically":

Catzie

A Filipino programmer and baker. When I have time to spare, I blog, play video games, watch series (usually anime), cook dishes, draw, or spend a little time with pets. When I have the rare luxury of time, I get to travel and record song covers too! Running small-time online dessert shops Cookies PH and Catzie's Cakery.

Leave a Reply

Your email address will not be published. Required fields are marked *