I need to scroll vertically (up and down) and horizontally (left and right) using appium + selenium + java. Can anyone please help me with snippet of the code required for this with explanation so I can use it further in other projects.
2 Answers
To Swipe right to left use below code
Dimension size = driver.manage().window().getSize();
int startx = (int) (size.width * 0.8);
int endx = (int) (size.width * 0.20);
int starty = size.height / 2;
driver.swipe(startx, starty, endx, starty, 1000);
left to right : the direction simply change start-x to end-x and end-x to startx
To swipe up/down : x-axis co-ordinates will remain same only y-coordinates will change.
If you are curious to know more about co-ordinates then turn on "Pointer location" setting from "Developer options" and observe co-ordinates manually.
1 Comment
Ashwin Pajankar
Thanks a ton. I will try this solution.
public static void swipe(MobileDriver driver, DIRECTION direction, long duration) {
Dimension size = driver.manage().window().getSize();
int startX = 0;
int endX = 0;
int startY = 0;
int endY = 0;
switch (direction){
case RIGHT:
startY = (int) (size.height /2);
startX = (int) (size.width * 0.90);
endX = (int) (size.width * 0.05);
break;
case LEFT:
startY = (int) (size.height /2);
startX = (int) (size.width * 0.05);
endX = (int) (size.width * 0.90);
break;
case UP:
endY= (int) (size.height * 0.70);
startY = (int) (size.height * 0.30);
startX = (size.width / 2);
break;
case DOWN:
startY = (int) (size.height * 0.70);
endY = (int) (size.height * 0.30);
startX = (size.width / 2);
break;
}
new TouchAction(driver)
.press(startX, startY)
.waitAction(Duration.ofMillis(duration))
.moveTo(endX, startY)
.release()
.perform();
}
Here is sample code for swiping in all directions. Just provide direction and duration of swipe.
Code is proven good.