Appium:如何遍历未知长度的列表视图?

Appium: How to iterate over a listview of unknown length?

我有一个列表视图,其中包含理论上我不知道的层次结构。我试图接受一个字符串数组并为其中的每个字符串创建 MobileElements,但是由于我通过注释自动 (PageFactory) 定义我的元素的方式,它们不能使用变量。我也不知道在方法中定义我的注释是否有效或合适。

我写的代码,显然不能编译如下:

public void selectLocation(String[] location) {

    List<MobileElement> locationsList = new ArrayList<>();
    for(int i = 0; i < location.length; i++) {

        @iOSFindBy(accessibility = location[i])
        @AndroidFindBy(xpath = "//android.widget.TextView[@text='" + location[i] + "']")
        locationsList.add(i);
    }
    for (int i = 0; i < location.length; i++) {
        locationsList.get(i).click();
    }
}

我假设执行此操作的正确方法与我实施的方法完全不同。

我的列表层次结构类似于以下内容;我的终点可能会因我走的分支而异:

我最终使用 "FindsBys" 函数创建了一个包含所有匹配元素的数组。然后我遍历这些元素以寻找与我的字符串之一的匹配项。

@AndroidFindBys({@AndroidFindBy(xpath = "//android.widget.TextView")})
@iOSFindBys({@iOSFindBy(xpath = "//XCUIElementTypeStaticText")})
private List<MobileElement> locationsList;

...

public void selectLocation(String[] location)
{
    for(int i = 0; i < locationsList.size(); i++)
        for(int p = 0; p < location.length; p++) {
            if (locationsList.get(i).getText().equals(location[p])) {
                locationsList.get(i).click();
            }
        }
}

它不是万无一失的(如果您在层次结构的不同级别有重复的字符串,您可能 运行 会遇到问题),但它适用于我的用例并且应该能够指导任何寻找更强大的解决方案。

您可以只遍历元素本身。

.....

for(MobileElement location: locationsList) {
    for(int p = 0; p < location.length; p++) {
        if (location.getText().equals(location[p])) {
            location.click();
        }
    }
}

我现在正在寻找匹配的元素。如果我没有找到它,我会进一步滑动到列表中。如果该元素不存在,我显然 运行 会遇到问题,但在我的情况下并不是真正的问题,因为那将是一个失败的测试。

while (!driver.findElementById(currentLocation).isDisplayed()) {
   driver.swipe(startX, startY, startX, endY, 100);
}
driver.findElementById(currentLocation).click();

是的,我也意识到 .swipe() 已被弃用,但它对我仍然有效,我宁愿在必要时不使用 TouchActions 重写我的所有代码。