Guide to Scrolling and Clicking an Element in Android with Appium and Java

Guide to Scrolling and Clicking an Element in Android with Appium and Java

5 April 2024 Stephan Petzl Leave a comment Tech-Help

When automating tests for Android applications using Appium and Java, a common scenario you might encounter is the need to scroll through a list to find and interact with a specific element. This is particularly true for lists that are longer than the screen can display at one time, such as a “RecyclerView”.

This guide will provide you with a method to scroll to an element with a specific text and click on it, even if the element is not immediately visible on the screen.

Understanding the Problem

Suppose you have a “RecyclerView” with a list of elements, all sharing the same ID but differing in their text values (e.g., “Apple”, “Orange”, “Grapes”…). You want to programmatically scroll through the list until you find the element with the text you’re looking for and then click on it.

Proposed Solution

To accomplish this, we can use the Android UIAutomator’s “UiScrollable” and “UiSelector” classes within our Appium test. Here’s a function that encapsulates the scrolling and clicking action based on the visible text of the element:

        
public void scrollAndClick(String visibleText) {
    androidDriver.findElementByAndroidUIAutomator("new UiScrollable(new UiSelector().scrollable(true).instance(0)).scrollIntoView(new UiSelector().textContains(\""+visibleText+"\").instance(0))").click();
}
        
    

How to Use the Function

To use this function within your test, simply call it with the text value of the element you wish to interact with:

        
scrollAndClick("Apple"); // Replace "Apple" with the text of the element you want to click
        
    

Explanation of the Code

The function scrollAndClick uses the findElementByAndroidUIAutomator method to create a UiScrollable object that can scroll through elements that are part of a scrollable layout. The scrollIntoView method is then used with a UiSelector that contains the text of the element we are looking for. Once the element is found, the click method is called to simulate the tap action.

Benefits of This Method

  • Efficiency: This method quickly scrolls to the desired element without the need for complex loops or additional logic.
  • Readability: Encapsulating the scrolling and clicking behavior in a single function makes the test code cleaner and easier to understand.
  • Reusability: The function can be reused across different tests with different text values for various elements.

Conclusion

Scrolling to an off-screen element in an Android application using Appium and Java can be effectively achieved by leveraging the UIAutomator’s “UiScrollable” and “UiSelector” classes. By using the provided scrollAndClick function, you can easily scroll to and interact with elements within a “RecyclerView” or any scrollable view.

Like this article? there’s more where that came from!