Implementing Long‑Press Actions in Android UiAutomator Tests

This guide shows how to create reusable UiAutomator helper methods that perform long‑press actions on Android UI elements—by resource ID, visible text, or explicit coordinates—using a swipe call with a 300‑step duration, and mentions extending the approach to custom gesture paths.

FunTester
FunTester
FunTester
Implementing Long‑Press Actions in Android UiAutomator Tests

When testing Android applications with UiAutomator, certain controls (e.g., a record button) require a press-and-hold gesture. The built‑in API for long press is cumbersome, so a lightweight custom solution is presented.

The core idea is to use UiDevice.getInstance().swipe() with identical start and end coordinates; the last parameter specifies the duration in units of 5 ms. A value of 300 therefore yields a 1.5‑second press.

/* Long press by resourceId */
public void longclickUiObectByResourceId(String id) throws UiObjectNotFoundException {
    int x = getUiObjectByResourceId(id).getBounds().centerX();
    int y = getUiObjectByResourceId(id).getBounds().centerY();
    UiDevice.getInstance().swipe(x, y, x, y, 300); // duration unit = 5 ms
}

/* Long press by visible text */
public void longclickUiObectByText(String text) throws UiObjectNotFoundException {
    int x = getUiObjectByText(text).getBounds().centerX();
    int y = getUiObjectByText(text).getBounds().centerY();
    UiDevice.getInstance().swipe(x, y, x, y, 300);
}

/* Long press by explicit coordinates */
public void longclickUiObectByCoordinates(int x, int y) throws UiObjectNotFoundException {
    UiDevice.getInstance().swipe(x, y, x, y, 300);
}

These three overloads cover the most common scenarios: locating a UI element by its resource ID, by the text it displays, or by a known coordinate pair. The same pattern can be extended to other selectors such as class name, index, or content description.

For more advanced gestures—e.g., drawing a heart shape with a series of points—a separate method that feeds an array of coordinates to swipe (or drag) can be used; the original article links to an example implementation.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

AndroidAutomationUI testingUIAutomatorLong Press
FunTester
Written by

FunTester

10k followers, 1k articles | completely useless

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.