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

北战南征 提交于 2019-11-30 08:27:18

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 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;
    }
}

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

recently found that we could use getFromParent (for UiObject) and fromParent (for UiSelector) to select an uncle of object for example. If we have such layout:

`LinearLayout
    relative layout
        text View
    relative layout
        check box`

we could get checkbox from textview with this code:

TextViewTitle().getFromParent(new UiSelector()
            .fromParent(new UiSelector()
                    .resourceId("android:id/checkbox")));

where TextViewTitle is a Uiobject with text view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!