Espresso Recyclerview 滚动到结束

Espresso Recyclerview scroll to end

我有一个 Android 应用程序,它有一个带有 N 个元素的 RecyclerView,当这个 RecyclerView 在滚动时到达终点时,会添加更多元素(因此,它是一个无限列表,在滚动到达时加载数据底部)。

我想对此进行测试,但我还没有找到执行此操作的方法。我使用具有 scrollToPosition 的 RecyclerViewActions,但即使我放置最后一个位置,也没有到达终点(因为每个元素的高度都很高)。

有人知道我该怎么做吗?

我使用下方滚动到我 RecyclerView 的底部。

activity = mActivityTestRule.launchActivity(startingIntent);

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

当加载更多数据时,您必须使用 idling resources(或 Thread.sleep())再次调用它。

我用这个;

 // 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));

您可以实现 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())