I'm wondering how I would be able to find a specific item in a recycler view where the order of items is randomized each run.
Let's assume I have 4 items in the recycler view, each represented by the same type of view holder with a text view in it. A unique title is applied to each view holder/item. For this example let's say the titles are, for simplicity's sake, "A", "B", "C", and "D".
How would I find the position (and then click) item "A" if the order is randomized? I know if the order does not change I could the scrollToPosition RecyclerViewInteraction action, but in this case the order can and will change.
Any thoughts?
To interact with RecyclerViews using Espresso, you can use the espresso-contrib package, which has a collection of RecyclerViewActions that can be used to scroll to positions or to perform actions on items: scrollTo() - Scrolls to the matched View, if it exists.
RecyclerView will go to Adapter and request it to create new ViewHolder from the ViewType . Adapter will create a new ViewHolder and bind it with the data for the requested position . Adapter will return ViewHolder to RecyclerView and RecyclerView return the View back to LayoutManger .
I was able to get this to work doing the following:
Matcher<RecyclerView.ViewHolder> matcher = CustomMatcher.withTitle("A");
onView((withId(R.id.recycler_view))).perform(scrollToHolder(matcher), actionOnHolderItem(matcher, click()));
Where CustomMatcher.withTitle
is:
public static Matcher<RecyclerView.ViewHolder> withTitle(final String title)
{
return new BoundedMatcher<RecyclerView.ViewHolder, CustomListAdapter.ItemViewHolder>(CustomListAdapter.ItemViewHolder.class)
{
@Override
protected boolean matchesSafely(CustomListAdapter.ItemViewHolder item)
{
return item.mTitleView.getText().toString().equalsIgnoreCase(title);
}
@Override
public void describeTo(Description description)
{
description.appendText("view holder with title: " + title);
}
};
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With