UI Automator / Ui Automator2:在Recycler View中滚动并查找子UI元素

时间:2017-11-14 06:23:17

标签: android uiautomator android-uiautomator

我想要实现这样的目标。
    打开Gmail应用,查找特定邮件(也可以滚动)并点击它   在下面的方法中,我可以搜索特定的邮件并单击它。

public void openMailWithParticularTitle(){
        UiObject2 obj =  Utils.getDeviceInstance().findObject(By.res("com.google.android.gm:id/recycler_list_view"));
        List<UiObject2> mails = obj.findObjects(By.clazz("android.view.View"));
        for(int i =0; i<mails.size();i++){
            if(mails.get(i).getContentDescription()!=null && mails.get(i).getContentDescription().contains("My Mail Link")){
                mails.get(i).click();
                break;
            }
        }
    }

但它只查找可见项目,不会滚动查找子元素 所以我环顾四周尝试了这个,但由于某些原因,这似乎也无法奏效。

 public void scrollMailWithParticularTitle2() throws UiObjectNotFoundException {
        openApp(Const.package_gmail_app,true);
        UiScrollable settingsItem = new UiScrollable(new UiSelector()
                .className("android.support.v7.widget.RecyclerView"));
        UiObject about = settingsItem.getChildByText(new UiSelector()
                .className("android.view.View"), "My Mail Link");
        about.click();
    }

任何帮助/建议都将不胜感激。 (我对UI测试的知识有限)

2 个答案:

答案 0 :(得分:2)

对于UIAutomator2;我已经创建了这两种方法,并且正在为我工​​作:

//This method returns child from scrollable parent using description


 public UiObject findChildFromScrollParentByDescription(String scrollParentClass, String childItemClass, String childDesc) throws UiObjectNotFoundException {
        UiScrollable parent = new UiScrollable(new UiSelector()
                .className(scrollParentClass));
        UiObject child = parent.getChildByDescription(new UiSelector()
                .className(childItemClass), childDesc, true);
        return child;
    }

//This method returns child from scrollable parent using text
public UiObject findChildFromScrollParentByText(String scrollParentClass, String childItemClass, String childDesc) throws UiObjectNotFoundException {
    UiScrollable parent = new UiScrollable(new UiSelector()
            .className(scrollParentClass));
    UiObject child = parent.getChildByText(new UiSelector()
            .className(childItemClass), childDesc, true);
    return child;
}

答案 1 :(得分:1)

尝试scrollIntoView功能:

  

执行向前滚动操作以在可滚动布局元素中移动,直到找到与选择器匹配的可见项目

我用过一次在应用菜单中找到我的应用:

UiDevice mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
UiObject allAppsButton = mDevice.findObject(new UiSelector().description("Apps"));
allAppsButton.clickAndWaitForNewWindow();

UiScrollable appView = new UiScrollable(new UiSelector().scrollable(true));
appView.scrollIntoView(new UiSelector().text(APP_TITLE));
mDevice.findObject(new UiSelector().text(APP_TITLE)).clickAndWaitForNewWindow();