如何使用 TouchAction 在 Appium 1.7.1 中滚动

How to scroll with Appium 1.7.1 using TouchAction

我在向下滚动到 iOS 和 Android 应用程序中的某个元素时遇到问题。自从 Appium 1.6.3 更新到 1.7.1 和 io.appium 更新到 6.1.0 以来,不推荐使用滑动方法,唯一的解决方案是使用 TouchActions。

我尝试用TouchActions解决,但是根本不滚动或者滚动方向不对。

到目前为止我的解决方案是这样的,也许有人可以解释我做错了什么:

public void scrollDownUntilElementVisible(WebElement element){
    TouchAction touchAction = new TouchAction(getDriver());
    for(int i=0; i<dimensions.getHeight();i++){
       if(element.isDisplayed()){
          break;
       }else{
          touchAction.press(0,0).moveTo(element).release().perform();
       }
    }
}

这不是完整的代码,但希望您能理解。

如果我使用 x,y 坐标而不是我在示例中查找的 webElement,它会如何工作?它不像以前版本的滑动方法那样工作,或者我没有做对。也许有人可以解释一下。

我需要滚动才能找到屏幕外的元素。我想出的是:

  1. 在 current/visible 屏幕上搜索您需要的元素。
  2. 如果未找到该元素(即超出屏幕)- scrollDown(在我的情况下,我只需要向下滚动)并再次转到第 1 步。我已将测试限制为 4 次迭代,因为在我的情况下就足够了,因此请在此处使用您自己的条件。
private void scrollDown() {
    //if pressX was zero it didn't work for me
    int pressX = driver.manage().window().getSize().width / 2;
    // 4/5 of the screen as the bottom finger-press point
    int bottomY = driver.manage().window().getSize().height * 4/5;
    // just non zero point, as it didn't scroll to zero normally
    int topY = driver.manage().window().getSize().height / 8;
    //scroll with TouchAction by itself
    scroll(pressX, bottomY, pressX, topY);
}

/*
 * don't forget that it's "natural scroll" where 
 * fromY is the point where you press the and toY where you release it
 */
private void scroll(int fromX, int fromY, int toX, int toY) {
    TouchAction touchAction = new TouchAction(driver);
    touchAction.longPress(fromX, fromY).moveTo(toX, toY).release().perform();
}

P.S。您可以从元素中获取坐标并在 scroll.

中使用它

P.S.S.我用的是 appium 1.6.5

在最新版本的 Appium 上需要添加(PointOption.point 同时传递坐标)一些使用 TouchAction 滚动的代码:

private void scrollDown() {
    //if pressX was zero it didn't work for me
    int pressX = driver.manage().window().getSize().width / 2;
    // 4/5 of the screen as the bottom finger-press point
    int bottomY = driver.manage().window().getSize().height * 4/5;
    // just non zero point, as it didn't scroll to zero normally
    int topY = driver.manage().window().getSize().height / 8;
    //scroll with TouchAction by itself
    scroll(pressX, bottomY, pressX, topY);
}



private void scroll(int fromX, int fromY, int toX, int toY) {
    TouchAction touchAction = new TouchAction(driver);
    touchAction.longPress(PointOption.point(fromX, fromY)).moveTo(PointOption.point(toX, toY)).release().perform();
}