Tapping on an element in Android app in Appium

Below example illustrates how to tap on an element in an Android app in Appium. Note that we have used io.appium.java_client.TouchAction class to tap on 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.Dimension;
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 TappingElementInWhatsappOnAndroidPhone
{
    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"));

            //You can use TouchAction Class
            //new TouchAction(driver).tap(contactsTextViewElement).perform();

            //or you can also use below syntax
            driver.performTouchAction(new TouchAction(driver).tap(contactsTextViewElement));
            
        }catch(Exception ex) {
            System.out.println(ex.toString());
        }finally {
            //quit the browser
            driver.quit();
        }
    }
}

You may also like...