UIautomator how to get child by index or instance

user3832387 picture user3832387 · Oct 16, 2014 · Viewed 9k times · Source

I use following code get child of uiautomator but not working

    UiObject my = new UiObject(new UiSelector().className("android.widget.LinearLayout").instance(2));

    int cound = my.getChildCount();
    for(int i = cound - 1; i >= 0; i--) {
        UiObject childmy2 = my.getChild(my.getSelector().childSelector(new UiSelector().instance(i)));
        Log.e("xface", "childmy2=" + childmy2.getClassName());
        Log.e("xface", "childmy2=" + childmy2.getBounds().toString());
    }

can anybody help me ?

simplyfy my question:how to implementation this function:

ArrayList getAllChild(UiObject node)

input:given node you want to getchild

return:all the child of the given node

Answer

Amit Kumar picture Amit Kumar · Dec 5, 2014

Suppose you have:

<parent>
    <child1>
          <child1.1></child1.1>
          <child1.2></child1.2>
    </child1>
    <child2>
          <child2.1></child2.1>
          <child2.2></child2.2>
    </child2>
    <child3>
          <child3.1></child3.1>
          <child3.2></child3.2>
    </child3>
</parent>

Bellow solution will return the result Child 1, Child 2, Child 3

UiObject object = new UiObject(<UiSelector for Parent>);
int cnt = object.getChildCount();
for(int i = 0; i < cnt; i++) {
   UiObject eachItem = object.getChild(new UiSelector().index(i));
}

If you want child 1.1, child 1.2 and child 2.1

UiObject object = new UiObject(<UiSelector for Parent>);
int cnt = object.getChildCount();
for(int i = 0; i < cnt; i++) {
    UiObject eachItem = object.getChild(new UiSelector().index(i))
                              .getChild(<UiSelector for child 1.1 or child 1.2 ...>);
// Note: Before getting this you should check whether it has any child or not.
}