UiObject in UIAutomator2 - Notes By ShariqSP
Understanding UiObject in UIAutomator2
The UiObject class is a core component of UIAutomator2, used to interact with UI elements in Android applications. It provides methods for locating and manipulating elements based on their attributes such as resource ID, text, description, or class name. Below, we explore its usage in detail.
1. Creating a UiObject
A UiObject instance is created using a UiSelector, which defines the criteria for locating the UI element. The criteria can include attributes like resourceId, text, or className.
// Create a UiObject for an element with a specific resource ID
UiObject button = new UiSelector().resourceId("com.example.app:id/button_id").makeUiObject();
2. Interacting with UiObject
The UiObject class provides various methods to perform actions such as clicking, setting text, checking visibility, and more:
- Click: Simulates a tap on the UI element.
- Set Text: Inputs text into editable fields.
- Get Text: Retrieves the text displayed on the element.
- Is Enabled: Checks if the element is enabled.
- Is Visible: Verifies if the element is currently visible on the screen.
// Perform actions on the UiObject
button.click();
String buttonText = button.getText();
boolean isEnabled = button.isEnabled();
3. Handling Dynamic Elements
In scenarios where elements may load asynchronously, use the waitForExists() method to wait for the element to appear before interacting with it.
// Wait for the element to exist
if (!button.waitForExists(5000)) {
throw new AssertionError("Button not found within the timeout period");
}
button.click();
4. Nested UiObjects
To interact with elements inside a container (e.g., a list or a dropdown), create a nested UiObject. Use the UiSelector to refine the search within the parent element.
// Locate a parent container
UiObject container = new UiSelector().resourceId("com.example.app:id/container_id").makeUiObject();
// Locate a child element within the container
UiObject childElement = container.getChild(new UiSelector().text("Child Text"));
childElement.click();
5. Common Issues and Debugging
- Element Not Found: Ensure the locator attributes (e.g., resource ID, text) are correct and unique.
- Timeouts: Increase the timeout value in
waitForExists()for slower loading elements. - Interaction Fails: Check if the element is enabled and visible before performing actions.
Example Code
// Full example using UiObject
UiObject button = new UiSelector().resourceId("com.example.app:id/button_id").makeUiObject();
if (!button.waitForExists(5000)) {
throw new AssertionError("Button not found");
}
button.click();
String buttonText = button.getText();
assert buttonText.equals("Submit") : "Button text mismatch";
6. Best Practices
- Use descriptive locators (e.g., resource IDs) for better reliability.
- Combine multiple attributes in
UiSelectorfor more precise targeting. - Handle dynamic content with adequate wait mechanisms.