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

匿名 (未验证) 提交于 2018-03-20 02:02:49

问题:

I'm trying to identify the parent view of an ui element so I can navigate through the UI freely.

For example, in Settings app, I can find the view with the text "Bluetooth":

UiObject btView = new UiObject(new UiSelector().text("Bluetooth"));

Now, the part where I get stuck is this one: I want to navigate two levels up and start a new search for the on/off button that enables and disables bluetooth.

Note: I can get the button if I use the code below.

UiObject btButtonView = new UiObject(new UiSelector().className("android.widget.Switch").instance(1));

This searches for switch buttons and returns the second encounter. I want the search to be more precise and look for the button in the linear layout that contains the "Bluetooth" text.

UPDATE: This is the layout of the Settings app (the Bluetooth part that I need):

LinearLayout
    LinearLayout
        ImageView
    RelativeLayout
        TextView (with text = "Bluetooth")
    Switch ()

回答1:

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


回答2:

Below code works for me.

//Getting the scrollable view

UiScrollable settingsList = new UiScrollable(new UiSelector().scrollable(true));

for (int i=0; i


回答3:

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


回答4:

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



每周VPS推荐 总有一款是你需要的!

没有找到想要的?点击这里去栏目页查看所有|点击这里搜索更多

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
如果有服务商和本站有合作意向,可以联系站长,QQ:121274060|邮箱:admin@e-learn.cn
了解到有朋友期望能在易学教程发布文章,奈何用户发布系统不完善,所以开通了码农岛,以供发布文章的需求
码农岛发布的文章需要同步到主站,可以加群联系群主
广告合作  |  商家投稿  |  易学教程交流群