How can I get the parent of a view using uiautomator? How can I get the parent of a view using uiautomator? android android

How can I get the parent of a view using uiautomator?


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();


Below code works for me.

//Getting the scrollable viewUiScrollable 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 viewUiObject 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;    }}


If you want to just search for ON/OFF slider -> You can directly search for bluetooth OFF/ON button and click on it to disable/enable bluetooth -

You can check screenshot of the bluetooth page(using command - uiautomatorviewer) in command prompt and see that OFF button will have text in the OFF/ON slider. Then simply use -

   new UiObject(new UiSelector().text("OFF")).click();