Search code examples
androidandroid-recyclerviewandroid-viewpagerandroid-espresso

Match RecyclerView by its position in ViewPager using Espresso


I am having a ViewPager with 3 Items, each Item is using same Fragment and hence same Recycler View. My View Hierarchy is like this,

-ViewPager  
----LinearLayout (id = ll) 
--------RecyclerView (id = rv) 
----LinearLayout (id = ll) 
--------RecyclerView (id = rv) 
----LinearLayout (id = ll)
--------RecyclerView (id = rv)

All have same ID's as they are same Layouts.

How do I distinguish these same 3 Identical RecyclerViews from the View Hierarchy ?


Solution

  • First create a matcher used for selecting the i-th matching view:

    public static <T> Matcher<T> result(final Matcher<T> matcher, final int i) {
        return new BaseMatcher<T>() {
            private int resultIndex = -1;
            @Override
            public boolean matches(final Object item) {
                if (matcher.matches(item)) {
                    resultIndex++;
                    return resultIndex == i;
                }
                return false;
            }
    
            @Override
            public void describeTo(final Description description) {
            }
        };
    }
    

    Then, use it as below:

    //select the second recycler view
    int i = 1;
    //then click on the first item of it
    int itemPosition = 0;
    onview(result(withId(R.id.rv), i)).perform(RecyclerViewActions.actionOnItemAtPosition(itemPosition, click()));