Espresso RecyclerView 滚动到底部

21

我有一个安卓应用,其中包含一个带有N个元素的RecyclerView。当滚动到底部时,会添加更多的元素(因此它是一个无限列表,在滚动到底部时加载数据)。

我想测试这个功能,但是我还没有找到一种方法。我使用了RecyclerViewActions中的scrollToPosition,即使我将其滚动到最后一个位置,也无法到达结尾(因为每个元素的高度都很高)。

有人知道我该怎么做吗?


如果在测试期间执行了拖动事件怎么办?就像这样 - https://qathread.blogspot.com/2014/01/discovering-espresso-for-android-swiping.html - Shmuel
1
测试速度非常快,我没有足够的时间向下滑动。我还尝试使用Espresso Recorder,但拖动事件未被捕获。 - LordWater
3个回答

28

我使用以下代码将RecyclerView滚动到底部。

activity = mActivityTestRule.launchActivity(startingIntent);

onView(withId(R.id.recyclerView)).perform(
    RecyclerViewActions.scrollToPosition<RecyclerView.ViewHolder>(
        activity.recyclerView.getAdapter().getItemCount() - 1
    )
);

接下来,您将需要使用空闲资源(或Thread.sleep())在更多数据加载时再次调用此函数。


我之前不知道RV有自己的滚动条,谢谢提醒。 - Zeek Aran
问题陈述中提到他已经在使用这个方法了。但是由于最后一个元素比屏幕大,因此无法滚动到底部。scrollToPosition只会滚动到项目的顶部边缘。因此,一个比屏幕大的项目仍然会有部分隐藏在屏幕底部边缘以下。我也遇到了同样的问题,即使使用了这段代码。我有点困惑为什么这被接受了,因为它只会滚动到最后一个元素的顶部,而不是RecyclerView的最底部。 - Emil S.
1
现在,ScrollToposition将ViewHolder名称作为类型。建议对其进行修改。 - srv_sud

15

你可以像这样实现ViewAction:

class ScrollToBottomAction : ViewAction {
override fun getDescription(): String {
    return "scroll RecyclerView to bottom"
}

override fun getConstraints(): Matcher<View> {
    return allOf<View>(isAssignableFrom(RecyclerView::class.java), isDisplayed())
}

override fun perform(uiController: UiController?, view: View?) {
    val recyclerView = view as RecyclerView
    val itemCount = recyclerView.adapter?.itemCount
    val position = itemCount?.minus(1) ?: 0
    recyclerView.scrollToPosition(position)
    uiController?.loopMainThreadUntilIdle()
}
}

然后像这样使用它:

onView(withId(R.id.recyclerView)).perform(ScrollToBottomAction())

你是个大师。 - BollMose

4
我使用这个;
 // Get total item of myRecyclerView
RecyclerView recyclerView = mActivityTestRule.getActivity().findViewById(R.id.myRecyclerView);
int itemCount = recyclerView.getAdapter().getItemCount();

Log.d("Item count is ", String.valueOf(itemCount));

// Scroll to end of page with position
onView(withId(R.id.myRecyclerView))
    .perform(RecyclerViewActions.scrollToPosition(itemCount - 1));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接