How to click on an item inside a RecyclerView in Espresso

前端 未结 10 2302
逝去的感伤
逝去的感伤 2020-12-01 05:33

I have a RecyclerView (R.id.recyclerView) where each row has an image (R.id.row_image) and a TextView. I want to click on the image in the first row.
I\'ve tried to use

10条回答
  •  粉色の甜心
    2020-12-01 05:53

    I have found two ways:

    1. Assuming you have a textview with id "R.id.description" for each item in the RecyclerView. You can do this to match a specific child:

    onView(allOf(withId(R.id.place_description),withText("what"))).perform(click());

    1. A tutorial from Android Testing Codelab https://codelabs.developers.google.com/codelabs/android-testing/#0

    `

    public Matcher withItemText(final String itemText) {
            checkArgument(!TextUtils.isEmpty(itemText),"cannot be null");
            return new TypeSafeMatcher() {
                @Override
                protected boolean matchesSafely(View item) {
                    return allOf(isDescendantOfA(isAssignableFrom(RecyclerView.class)),withText(itemText)).matches(item);
                }
    
                @Override
                public void describeTo(Description description) {
                    description.appendText("is descendant of a RecyclerView with text" + itemText);
                }
            };
        }
    

    `

    And then, do this:

    onView(withItemText("what")).perform(click());
    

提交回复
热议问题