There are multiple ways to do same thing but, we always prefer the optimized way. Same is the case for locating Android app elements.
You can locate Android app elements using :
- Appium inspector
The uiautomatorviewer is GUI tool to scan and analyze the UI components of an Android application. It provides a convenient visual interface to inspect the layout hierarchy and view the properties of the individual UI components that are displayed on the test device.
How to use a uiautomatorviewer.
- Connect Android device to the PC using a USB cable and enable USB debugging option from “Settings -> Developer options” .
- Launch your test application manually by tapping on the application icon (Here we are using Calculator app).
- Now open command prompt/terminal and hit command uiautomatorviewer. This command will open an empty uiautomatorviewer window.
- Click on Device Screenshot or Device Screenshot with Compressed Hierarchy option (2nd and 3rd option in upper left corner). You will get screenshot of currently open view of app on your device. (In our case android calculator screenshot get displayed)
- Now click on app element whose information you want, element will get highlighted in red and you will get element information under Node Details section in uiautomatorviewer window . (In our case lets consider we want information of key 8 of Calculator)
- Now we have index, text, resource-id,class, package and other info. You can use resource-id of element in script to locate element by id (In our case resource-id of key 8 is “com.android2.calculator3:id/digit8”)
- If any element does not have id then use xpath to locate the element. (Lets consider after tapping on key 8 you want to assert text 8).
- To write your xpath:
a. Start with the class //class
b. Add attributes @attribute=”attribute_value”
E.g.: XPath to identify the text 8 in the calculator app is “//android.widget.EditText[@index=0]”. We can use ‘text’, ‘content description’ and other attribute to write xpath.
To get information about Appium Inspector refer this link.