UIAutomator click listview based on index

Viewed 4950

I'm trying to implement an UIAutomator testcase with a general method to perform a click on a ListView item (regardless of the type of viewgroup holding the listitem).

Currently I have following code, but it keeps on clicking the first item.

public void clickListViewItem(int index) throws UiObjectNotFoundException {
   UiObject listview = new UiObject(new UiSelector().className("android.widget.ListView"));
   if(index <= listview.getChildCount()){
      listview.getChild(new UiSelector().index(index)).click();
   }else{
       throw new UIObjectNotFoundException("Index is greater than listSize");
   }
}
2 Answers

The developer page implements a similar scenario, found here - although this assumes there is some identifying feature that exists in the child by which to select (like in example below, a string "Apps"):

If more than one matching element is found, the first matching element in the layout hierarchy is returned as the target UiObject. When constructing a UiSelector, you can chain together multiple properties to refine your search. If no matching UI element is found, a UiAutomatorObjectNotFoundException is thrown.

You can use the childSelector() method to nest multiple UiSelector instances. For example, the following code example shows how your test might specify a search to find the first ListView in the currently displayed UI, then search within that ListView to find a UI element with the text property Apps.

val appItem: UiObject = device.findObject(
        UiSelector().className("android.widget.ListView")
                .instance(0)
                .childSelector(
                        UiSelector().text("Apps")
                )
)
Related