如何使用浓缩咖啡滚动到 RecyclerView-Item 的子项

How to use espresso to scroll to child of RecyclerView-Item

我正在为我的应用程序编写浓缩咖啡测试。对于一个测试,我必须单击 RecyclerView-Item 上的按钮。说的项目比屏幕大,所以当我滚动到项目时,所需的按钮仍然没有显示(这是必需的,所以我可以点击它)。

我尝试使用

滚动到视图
onView(withId(R.id.recycler_view)).perform(scrollTo<MyViewHolder>(hasDescendant(withId(R.id.target_button))))

但这只是滚动到包含该按钮的项目的顶部。由于按钮位于该项目的最底部并且该项目比屏幕大,因此当我尝试单击该按钮时我得到

Action will not be performed because the target view does not match one or more of the following constraints:
at least 90 percent of the view's area is displayed to the user.

我也试过了

onView(withId(R.id.recycler_view)).perform(actionOnItemAtPosition<MyViewHolder>(0, EspressoUtils.clickChildViewWithId(R.id.target_button)))

其中 EspressoUtils.clickChildViewWithId(id: Int) 问题的已接受答案中描述的内容。这也产生了同样的错误。如何滚动到 RecyclerView-Item 中的特定子项?

当我在比我的屏幕大两倍的 RecyclerView 项目中单击视图时,以下解决方案适用于我。注意:我点击的视图实际上不在屏幕上,但由于它在视图层次结构中,所以可以点击它。

创建自定义 ViewAction:

private fun clickChildViewWithId(id: Int) = object : ViewAction {

    override fun getConstraints() = null

    override fun getDescription() = "click child view with id $id"

    override fun perform(uiController: UiController, view: View) {
        val v = view.findViewById<View>(id)
        v.performClick()
    }
}

用法:

onView(withId(R.id.recycler_view))
            .perform(actionOnItemAtPosition<MyViewHolder>(0, clickChildViewWithId(R.id.target_button)))