我有一个安卓应用,其中包含一个带有N个元素的RecyclerView。当滚动到底部时,会添加更多的元素(因此它是一个无限列表,在滚动到底部时加载数据)。
我想测试这个功能,但是我还没有找到一种方法。我使用了RecyclerViewActions中的scrollToPosition,即使我将其滚动到最后一个位置,也无法到达结尾(因为每个元素的高度都很高)。
有人知道我该怎么做吗?
我有一个安卓应用,其中包含一个带有N个元素的RecyclerView。当滚动到底部时,会添加更多的元素(因此它是一个无限列表,在滚动到底部时加载数据)。
我想测试这个功能,但是我还没有找到一种方法。我使用了RecyclerViewActions中的scrollToPosition,即使我将其滚动到最后一个位置,也无法到达结尾(因为每个元素的高度都很高)。
有人知道我该怎么做吗?
我使用以下代码将RecyclerView
滚动到底部。
activity = mActivityTestRule.launchActivity(startingIntent);
onView(withId(R.id.recyclerView)).perform(
RecyclerViewActions.scrollToPosition<RecyclerView.ViewHolder>(
activity.recyclerView.getAdapter().getItemCount() - 1
)
);
接下来,您将需要使用空闲资源(或Thread.sleep()
)在更多数据加载时再次调用此函数。
你可以像这样实现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())
// 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));