2

一个屏幕上有多个水平Recyclerview。我想在第一个水平的第一项上执行浓缩咖啡点击事件Recyclerview。请让我知道我们如何实现它。

 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));
    }

它给了我以下例外:

android.support.test.espresso.AmbiguousViewMatcherException
4

1 回答 1

2

花了几个小时后,我找到了解决方案,我们需要使用 Matcher 来匹配RecyclerView多个水平中的第一个RecyclerView。将以下方法放在您的测试类中。

    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");
        }
    };
}

这是您如何使用它的代码片段,

  onView(firstView(withId(R.id.recyclerview_tray)))
            .perform(RecyclerViewActions.actionOnItemAtPosition(1, click()));
于 2017-08-29T06:55:17.520 回答