编写一个测试,点击PopupWindow内部的视图。

15

我有一个放在PopupWindow里的ListView,我想要点击列表中的第二项。我已经尝试了以下方法:

// Open the popupwindow
onView(withId(R.id.popupwindow_open)).perform(click()); 

现在弹出窗口出现了,我尝试了:

onData(anything()).inAdapterView(withContentDescription("delete")).atPosition(1).perform(
        click());

或者这个:

onView(withContentDescription("delete"))).perform(click());

但我总是得到视图未找到的错误。在Espresso中我该怎么做?


1
您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - Daniel Lubarov
1
.inAdapterView(withContentDescription("delete")) 的意思是 ListView 本身必须具有 "delete" 的 contentDescription。移除 inAdapterView 是否有效?即 onData(anything()).atPosition(1).perform(click());。此外,如果您发布完整的错误消息,将有助于我们更好地理解问题。 - yogurtearl
3个回答

40

Android系统的弹出窗口和警报是在一个不同的窗口中显示的。因此,您必须尝试在该特定窗口中查找视图,而不是主活动窗口。

Espresso提供了一种方便的方法来查找弹出窗口的根视图。请尝试此方法。

onView(ViewMatchers.withContentDescription("delete"))
         .inRoot(RootMatchers.isPlatformPopup())
         .perform(ViewActions.click());

7
你是一个救命恩人,在尝试了数小时所有的解决方案后,我希望这个方法能得到更多的票数:对我而言,使用文本搜索 onView(withText("Popup Selection 1")).inRoot(isPlatformPopup()).perform(click()) 能够解决问题。 - Mihaela Romanca
这篇文章和Miheala的评论帮了我很多。这个对我有用:onView(withText("Okay")).inRoot(RootMatchers.isPlatformPopup()).perform(click())。 - Richard Guion
同样的问题,使用了withText方法,内容描述也没有找到匹配的视图。感谢Mihaela和Nishanth,或许有机会改进原始答案。 - MG Developer

5

在你的情况下,你有两个不同的窗口。因此,要指定与Espresso交互的窗口,您必须使用Root matcher。尝试或稍微调整以下这些解决方案:

onView(withContentDescription("delete"))
    .inRoot(withDecorView(not(is(getActivity().getWindow().getDecorView()))))
    .perform(click());

或者
onData(withContentDescription("delete"))
    .inRoot(withDecorView(not(is(getActivity().getWindow().getDecorView()))))
    .inAdapterView(withId(R.id.adapter_view))
    .perform(click());

0

试试这个:

onView(withId(android.R.id.id_you_are_looking_for)).perform(click());

在我的情况下,我使用系统对话框,所以ID必须以“android”为前缀,这样它才能正常工作。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接