如何使用 Espresso 长按 RecyclerView 中的项目

How to long press an item in a RecyclerView using Espresso

验证我使用的 RV 中项目的文本字符串

private fun verifyItemName(pos: Int, name: String) =
    onView(
        RecyclerViewMatcher(R.id.recycler_view)
            .atPositionOnView(pos, R.id.text_view)
    ).check(matches(withText(name)))

其中 here 中的 RecyclerViewMatcher

class RecyclerViewMatcher(private val recyclerViewId: Int) {

    fun atPosition(position: Int): Matcher<View> {
        return atPositionOnView(position, -1)
    }

    fun atPositionOnView(position: Int, targetViewId: Int): Matcher<View> {
        return object : TypeSafeMatcher<View>() {
            var resources: Resources? = null
            var childView: View? = null

            override fun describeTo(description: Description) {
                var idDescription = recyclerViewId.toString()
                if (this.resources != null) {
                    idDescription = try {
                        this.resources!!.getResourceName(recyclerViewId)
                    } catch (var4: Resources.NotFoundException) {
                        "$recyclerViewId (resource name not found)"
                    }
                }

                description.appendText("RecyclerView with id: $idDescription at position: $position")
            }

            public override fun matchesSafely(view: View): Boolean {

                this.resources = view.resources

                if (childView == null) {
                    val recyclerView = view.rootView.findViewById<RecyclerView>(recyclerViewId)
                    if (recyclerView?.id == recyclerViewId) {
                        val viewHolder = recyclerView.findViewHolderForAdapterPosition(position)
                        childView = viewHolder?.itemView
                    } else {
                        return false
                    }
                }

                return if (targetViewId == -1) {
                    view === childView
                } else {
                    val targetView = childView?.findViewById<View>(targetViewId)
                    view === targetView
                }
            }
        }
    }
}

但是我怎样才能长按rv中的一个项目呢?

找到了

onView(
    RecyclerViewMatcher(R.id.rv_list)
        .atPositionOnView(0, R.id.iv_direction)
).perform(longClick())