You need to enable JavaScript to run this app. ESPRESSO如何点击NestedScrollView内RecyclerView未展示条目的内部按钮
优惠活动
大模型
产品
解决方案
定价
更多

ESPRESSO如何点击NestedScrollView内RecyclerView未展示条目的内部按钮

解决方法

你需要结合自定义滚动适配逻辑和Espresso的RecyclerView扩展能力实现操作,默认的scrollTo()方法不支持NestedScrollView,需要额外适配。

步骤1:引入必要依赖

首先在模块级build.gradle中引入Espresso的RecyclerView扩展库:

androidTestImplementation "androidx.test.espresso:espresso-contrib:3.5.1"

步骤2:实现NestedScrollView专属滚动动作

默认滚动方法仅支持普通ScrollView,自定义适配动作如下(Kotlin写法,Java可直接转译语法,逻辑不变):

fun nestedScrollTo(): ViewAction {
    return object : ViewAction {
        override fun getConstraints(): Matcher<View> {
            return allOf(
                isDescendantOfA(isAssignableFrom(NestedScrollView::class.java)),
                withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE)
            )
        }

        override fun getDescription(): String {
            return "滚动到NestedScrollView内的目标视图"
        }

        override fun perform(uiController: UiController, view: View) {
            val scrollView = ViewMatchers.getAncestorOfType(
                view, NestedScrollView::class.java, true
            ) as NestedScrollView
            scrollView.smoothScrollTo(0, view.top)
            uiController.loopMainThreadUntilIdle()
        }
    }
}

步骤3:执行目标按钮点击

有两种常用实现方式,可按需选择:

方式一:分步骤执行

// 1. 先让RecyclerView滚动到目标position
onView(withId(R.id.你的RecyclerView的ID))
    .perform(RecyclerViewActions.scrollToPosition<RecyclerView.ViewHolder>(目标position数值))

// 2. 定位目标按钮,滚动到可视区后点击
onView(
    allOf(
        isDescendantOfA(withId(R.id.你的RecyclerView的ID)),
        withId(R.id.目标按钮的ID)
    )
).perform(nestedScrollTo(), click())

方式二:封装成单次操作

onView(withId(R.id.你的RecyclerView的ID))
    .perform(
        RecyclerViewActions.actionOnItemAtPosition<RecyclerView.ViewHolder>(
            目标position数值,
            actionOnItemView(withId(R.id.目标按钮的ID), nestedScrollTo(), click())
        )
    )

注意事项

  • 执行测试前建议关闭RecyclerView的条目动画,避免动画未结束导致的点击失效
  • 两种方式都需要先触发RecyclerView的滚动,再处理NestedScrollView的滚动,避免滚动冲突

内容的提问来源于stack exchange,提问作者Leonardo Sibela

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 16:00:04