Espresso AmbiguousViewMatcherException:如何从多个水平Recyclerview中选择第一个水平Recyclerview

时间:2017-08-28 06:58:49

标签: android android-espresso android-junit androidjunitrunner

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

 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

1 个答案:

答案 0 :(得分:1)

花了几个小时后我找到了解决方案,我们需要使用匹配器匹配来自多个水平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()));