How can I use Espresso to click a specific view inside a RecyclerView item? I know I can click the item at position 0 using:
onView(withId(R.i
All of the answers above didn't work for me so I have built a new method that searches all of the views inside a cell to return the view with the ID requested. It requires two methods (could be combined into one):
fun performClickOnViewInCell(viewID: Int) = object : ViewAction {
override fun getConstraints(): org.hamcrest.Matcher = click().constraints
override fun getDescription() = "Click on a child view with specified id."
override fun perform(uiController: UiController, view: View) {
val allChildViews = getAllChildrenBFS(view)
for (child in allChildViews) {
if (child.id == viewID) {
child.callOnClick()
}
}
}
}
private fun getAllChildrenBFS(v: View): List {
val visited = ArrayList();
val unvisited = ArrayList();
unvisited.add(v);
while (!unvisited.isEmpty()) {
val child = unvisited.removeAt(0);
visited.add(child);
if (!(child is ViewGroup)) continue;
val group = child
val childCount = group.getChildCount();
for (i in 0 until childCount) { unvisited.add(group.getChildAt(i)) }
}
return visited;
}
Then final you can use this on Recycler View by doing the following:
onView(withId(R.id.recyclerView)).perform(actionOnItemAtPosition(0, getViewFromCell(R.id.cellInnerView) {
val requestedView = it
}))
You could use a callback to return the view if you want to do something else with it, or just build out 3-4 different versions of this to do any other tasks.