Pressing an element in Android app in Appium

Below example illustrates how to long press an element and simply press an element in Android App in Appium. As you can see, we have used TouchAction class to press an element.

package nativeapptests;

import io.appium.java_client.TouchAction;
import io.appium.java_client.android.AndroidDriver;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.net.URL;
import java.util.concurrent.TimeUnit;

public class PressingElementInWhatsappOnAndroidPhone
{
    private AndroidDriver driver;

    @Test
    public void tapTest() throws Exception{

        DesiredCapabilities capabilities = new DesiredCapabilities();
        capabilities.setCapability("platformName", "Android");
        capabilities.setCapability("platformVersion", "4.4.4");
        capabilities.setCapability("deviceName", "sagarcell");
        capabilities.setCapability("browser_Name", "Android");
        capabilities.setCapability("appPackage", "com.whatsapp");
        capabilities.setCapability("appActivity","com.whatsapp.Main");

        try {
            driver = new AndroidDriver(new URL("https://127.0.0.1:4723/wd/hub"), capabilities) {
            };

           driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
           new WebDriverWait(driver,20).
                   until(ExpectedConditions.elementToBeClickable(By.className("android.widget.TextView")));
           WebElement contactsTextViewElement =
                   driver.findElement(By.className("android.widget.TextView"));

            //long press the first chat contact in whatsapp
            new TouchAction(driver).longPress(contactsTextViewElement,2000);

            //press (tap) the first contact in whatsapp
            new TouchAction(driver).press(contactsTextViewElement);

        }catch(Exception ex) {
            System.out.println(ex.toString());
        }finally {
            //quit the browser
            driver.quit();
        }
    }
}

You may also like...