Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
605 views
in Technique[技术] by (71.8m points)

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

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 ()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...