Finding the center position of an element in Android app in Appium

Below example shows how to find the center position of an element in Android app using Appium. It also shows how to find the X and Y co-ordinates of the top left corner of the element.

package nativeapptests;

import io.appium.java_client.MobileElement;
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 FindingPositionOnAndroidPhone
{
    private AndroidDriver driver;

    @Test
    public void test() 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"));

            System.out.println("X co-ordinate of TextView "
                    + contactsTextViewElement.getLocation().getX());
            System.out.println("Y co-ordinate of TextView "
                    + contactsTextViewElement.getLocation().getY());

            System.out.println("X co-ordinate of center of TextView "
                    + ((MobileElement)contactsTextViewElement).getCenter().getX());
            System.out.println("Y co-ordinate of center of TextView "
                    + ((MobileElement)contactsTextViewElement).getCenter().getY());

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

Here is the output of above code.

X co-ordinate of TextView 123
Y co-ordinate of TextView 216
X co-ordinate of center of TextView 154
Y co-ordinate of center of TextView 234

You may also like...