基于索引的UIAutomator列表项点击

8

我正在尝试使用通用方法实现UIAutomator测试用例,从而在单击ListView项目时执行单击操作(无论包含列表项的视图组类型如何)。

目前,我有以下代码,但它一直在单击第一个项目。

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");
   }
}

你是不是把它放在了一个循环里?我认为这就是问题所在。 - Naveen Prince P
2个回答

14

我用以下代码使它正常工作,它基于UISelector的可点击属性:

listview.getChild(new UiSelector().clickable(true).index(index)).click();

1
如何检索ListView对象本身? - Behnam
无法在较新版本的UiAutomator中使用。 - Tobrun

1
开发者页面实现了类似的场景,可以在这里找到 - 尽管这假定存在某些可用于选择子项的标识特征(如下例中的字符串“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")
                )
)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接