首页 > 解决方案 > Android + Appium:在 ListView 内滚动到特定位置并单击它

问题描述

有人可以帮我解决这个问题。

任务:在 Android App 中打开 ListView 元素,滚动到特定位置并单击它。如果未找到元素,则滚动到列表底部并停止搜索并删除异常测试。 带有结构的应用程序屏幕截图

//是的,我一直在寻找其他问题的解决方案,但我无法将其结合起来用于我的案例。

我得到了什么:

1) 测试在 ListView 内滑动到特定位置并点击它;

2) 在 ListView 底部循环测试堆栈。

问题:

1)如果到达ListView底部时没有找到特定位置,如何停止测试?

2) 滑动看起来像不正确的解决方案,似乎必须使用其他解决方案,或者没有?

代码:

public void scrollToElementFromList (String keyword_locator){
// keyword_locator = (By.xpath("//*[@resource-id = 'android:id/text1'][@text = 'Spain']"))
    boolean token = false;
    while(!token) {
        if (this.isElementPresent(keyword_locator)){
            waitForElementAndClick(keyword_locator,"Cannot click selected element",3);
            token = true;
        } else {
            TouchAction action = new TouchAction(driver);
            WebElement element = driver.findElement(By.xpath("//android.widget.ListView"));
            int middleX = element.getLocation().getX() + element.getSize().getWidth() / 2;
            int upperY = element.getLocation().getY();
            int lowerY = upperY + element.getSize().getHeight() - 50;
            action.press(middleX, lowerY).waitAction(1200).moveTo(middleX, upperY).release().perform();
            continue;
        }
    }
}

标签: javaandroidlistviewappium

解决方案


回答:

public void scrollToElementFromList (String locator, String keyword_locator, int max_swipes){
    By by = this.getLocatorByString(locator);
    boolean element_found = false;
    int already_swiped = 0;
    while(!element_found) {
        if (this.isElementPresent(keyword_locator)){
            waitForElementAndClick(keyword_locator,"Cannot click selected element",3);
            element_found = true;
        } else if (already_swiped > max_swipes){
            throw new AssertionError("Cannot find element by swiping up.");
        }
        else {
            TouchAction action = new TouchAction(driver);
            WebElement element = driver.findElement(by);
            int middleX = element.getLocation().getX() + element.getSize().getWidth() / 2;
            int upperY = element.getLocation().getY();
            int lowerY = upperY + element.getSize().getHeight() - 50;
            action.press(middleX, lowerY).waitAction(1200).moveTo(middleX, upperY).release().perform();
            ++already_swiped;
            continue;
        }
    }
}

推荐阅读