Testing ViewPager with Espresso. How perfom action to a button of an Item?

后端 未结 1 932
生来不讨喜
生来不讨喜 2020-12-24 06:03

I have a ViewPager whith items containing only a picture and a button.

I can\'t successfully interact with the UI of an item (Page) because, except the

相关标签:
1条回答
  • 2020-12-24 06:55

    FirstVal, ViewPager is not an AdapterView, it directly extends from ViewGroup. So the method onData() cannot be used on a ViewPager.

    1. Solution

    As it's a ViewGroup, each items are direct children of its ViewPager. So the process is to reference the first view child using a custom matcher (like this onefirstChildOf()) and playing with hasDescendant() and isDescendantOfA() to access the targeted view and perform an action on it.

     onView(allOf(withId(R.id.button), isDescendantOfA(firstChildOf(withId(R.id.viewpager)))))
                .perform(click());
    

    2. Solution (da best)

    As the particularity of the ViewPager is to display each items (#1 solution's child views) that composed it, one by one (page-by-page style). So even if your items use the same layout with the same IDs, only one is displayed. So we can reference the targeted view by its Id and add the constraints isDisplayed(). It will match only one view, the one that is currently displayed.

    onView(allOf(withId(R.id.button), isDisplayed())).perform(click());
    

    as simple as that.

    And if you want another item, you may perform a swipe() on your ViewPager to change the displayed item:

    onView(withId(R.id.viewpager)).perform(swipeLeft());
    
    0 讨论(0)
提交回复
热议问题