There are multiple horizontal Recyclerview on a screen. I want to perform a espresso click event on first item of first horizontal Recyclerview. Please let me know how we can achieve it.

 onView(withId(R.id.craousal_recyclerview))
.perform(RecyclerViewActions.actionOnItemAtPosition(1, new ClickOnImageView()));

 public class ClickOnImageView implements ViewAction {
    ViewAction click = click();

    @Override
    public Matcher<View> getConstraints() {
        return click.getConstraints();
    }

    @Override
    public String getDescription() {
        return " click on custom image view";
    }

    @Override
    public void perform(UiController uiController, View view) {
        click.perform(uiController, view.findViewById(R.id.craousal_imageview));
    }

It's giving me the following exception:

android.support.test.espresso.AmbiguousViewMatcherException
1

There are 1 answers

0
chank007 On

After spending few hours I found the solution, we need to use a Matcher to match the first RecyclerView from multiple horizontal RecyclerView. Put the below method in your test class.

    private <T> Matcher<T> firstView(final Matcher<T> matcher) {
    return new BaseMatcher<T>() {
        boolean isFirst = true;

        @Override
        public boolean matches(final Object item) {
            if (isFirst && matcher.matches(item)) {
                isFirst = false;
                return true;
            }

            return false;
        }

        @Override
        public void describeTo(final Description description) {
            description.appendText("should return first matching item");
        }
    };
}

And here is the code snippet how you can use it,

  onView(firstView(withId(R.id.recyclerview_tray)))
            .perform(RecyclerViewActions.actionOnItemAtPosition(1, click()));