2

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
Alex M
  • 2,756
  • 7
  • 29
  • 35
chank007
  • 240
  • 2
  • 8
  • Can you post your layout files? There is likely a way to do this in your app without resorting to creating custom ViewActions, by using a more specific viewholder matcher with RecyclerViewAction. actionOnHolderItem() – jdonmoyer Aug 28 '17 at 15:08
  • @jdonmoyer I am creating layout at runtime in my code. By the I got the solution for it and I mentioned the answer. But now facing another issue that my `RecyclerView` adapter size is coming zero so I am not able to perform click on first item of list. But on screen I can see the data in my `RecyclerView`. Any input on it ? – chank007 Aug 29 '17 at 07:02

1 Answers1

2

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()));
chank007
  • 240
  • 2
  • 8