Java Code Examples for android.support.test.uiautomator.UiSelector.instance()

The following are Jave code examples for showing how to use instance() of the android.support.test.uiautomator.UiSelector class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: appium-uiautomator2-server   File: UiObjectElement.java   View Source Code Vote up 4 votes
public ArrayList<UiObject> getChildElements(final UiSelector sel) throws UiObjectNotFoundException {
    boolean keepSearching = true;
    final String selectorString = sel.toString();
    final boolean useIndex = selectorString.contains("CLASS_REGEX=");
    final boolean endsWithInstance = endsWithInstancePattern.matcher(selectorString).matches();
    Logger.debug("getElements selector:" + selectorString);
    final ArrayList<UiObject> elements = new ArrayList<UiObject>();

    // If sel is UiSelector[CLASS=android.widget.Button, INSTANCE=0]
    // then invoking instance with a non-0 argument will corrupt the selector.
    //
    // sel.instance(1) will transform the selector into:
    // UiSelector[CLASS=android.widget.Button, INSTANCE=1]
    //
    // The selector now points to an entirely different element.
    if (endsWithInstance) {
        Logger.debug("Selector ends with instance.");
        // There's exactly one element when using instance.
        UiObject instanceObj = Device.getUiDevice().findObject(sel);
        if (instanceObj != null && instanceObj.exists()) {
            elements.add(instanceObj);
        }
        return elements;
    }

    UiObject lastFoundObj;

    UiSelector tmp;
    int counter = 0;
    while (keepSearching) {
        if (element == null) {
            Logger.debug("Element] is null: (" + counter + ")");

            if (useIndex) {
                Logger.debug("  using index...");
                tmp = sel.index(counter);
            } else {
                tmp = sel.instance(counter);
            }

            Logger.debug("getElements tmp selector:" + tmp.toString());
            lastFoundObj = Device.getUiDevice().findObject(tmp);
        } else {
            Logger.debug("Element is " + getId() + ", counter: " + counter);
            lastFoundObj = element.getChild(sel.instance(counter));
        }
        counter++;
        if (lastFoundObj != null && lastFoundObj.exists()) {
            elements.add(lastFoundObj);
        } else {
            keepSearching = false;
        }
    }
    return elements;
}