cur4so
cur4so

Reputation: 1820

select a spinner element with uiautomator

I've tried multiple options. Neither worked for me. Is it possible to select an element of a spinner using uiautomator?

Code example:

UiObject spinner = mDevice.findObject(new UiSelector().className("android.widget.Spinner")
            .instance(0));

        try {
             Integer cnt = spinner.getChildCount();
             if (cnt > 0) {
                 UiObject item = spinner.getChild(new UiSelector().index(cnt-1));
                 item.click();
             }
        } catch (UiObjectNotFoundException e){}

Upvotes: 0

Views: 2242

Answers (2)

Martin Zeitler
Martin Zeitler

Reputation: 76589

One can select By.res, but without parameter packageName (which is android):

UiObject2 spinner = mDevice.findObject(By.res(packageName, "spinner"));
spinner.click();
sleep(2000);

List<UiObject2> items = mDevice.findObjects(By.res("android:id/text1"));
items.get(1).click(500);

Upvotes: 2

Diego Torres Milano
Diego Torres Milano

Reputation: 69198

This snippet will select an item from the Spinner

    (new UiScrollable(new UiSelector().resourceId("com.dtmilano.android.demoapplication:id/spinner").index(1).packageName("com.dtmilano.android.demoapplication"))).click();
    List<UiObject2> children = mDevice.findObjects(By.res("android:id/text1").pkg("com.dtmilano.android.demoapplication"));
    for (UiObject2 uio2 : children) {
        if ("New Zealand".equals(uio2.getText())) {
            uio2.click();
            break;
        }
    }

it's using a sample Activity with a Spinner showing countries

enter image description here

The first part was automatically generated by Enumerate Children feature of CulebraTester.

Upvotes: 1

Related Questions