How can I get the parent of a view using uiautomator?
Below code works for me.
//Getting the scrollable view
UiScrollable settingsList = new UiScrollable(new UiSelector().scrollable(true));
for (int i=0; i<=settingsList.getChildCount(new UiSelector ().className(LinearLayout.class.getName())); i++) {
//Looping through each linear layout view
UiObject linearLayout = settingsList.getChild(new UiSelector().className(LinearLayout.class.getName()).instance(i));
//Checking if linear layout have the text. If yes, get the switch, click and break out of the loop.
if (linearLayout.getChild(new UiSelector ().text("Bluetooth")).exists()) {
UiObject btSwitch = linearLayout.getChild(new UiSelector().className(android.widget.Switch.class.getName()));
btSwitch.click ();
break;
}
}
You need to find the UiObject two levels up first using the text. This can be done using the getChildByText()
methods in UiCollection or UiScrollable. Then you can easily find the switch. For 'Settings' this code works on my device:
UiScrollable settingsList = new UiScrollable(new UiSelector().scrollable(true));
UiObject btItem = settingsList.getChildByText(new UiSelector().className(LinearLayout.class.getName()),"Bluetooth", true);
UiObject btSwitch = btItem.getChild(new UiSelector().className(android.widget.Switch.class.getName()));
btSwitch.click();