我正在为 recyclerview 编写测试用例。我在 recyclerview 中进行了拖放测试。我以某种方式尝试过。但无法为 recyclerview 编写拖放测试。
在 recyclerview 中我有拖动按钮。使用该按钮,我将某个位置上的项目拖放到其他位置。
我的从下到上滑动的代码
onView(withId(R.id.recyclerView)).perform(
RecyclerViewActions.actionOnItemAtPosition(0, new GeneralSwipeAction(
Swipe.SLOW, GeneralLocation.BOTTOM_CENTER, GeneralLocation.TOP_CENTER,
Press.FINGER)));
这段代码是滑动recyclerview。
所以我尝试这样:
onView(withId(R.id.recyclerView)).perform(
RecyclerViewActions.actionOnItemAtPosition(0,
MyViewAction.clickChildViewWithId(R.id.img_drag)),new GeneralSwipeAction(
Swipe.SLOW, GeneralLocation.TOP_RIGHT, GeneralLocation.CENTER_RIGHT,
Press.FINGER));
但这对我来说不是锻炼。请告诉我任何测试拖放功能的想法。
最佳答案
您编写的代码首先单击拖动 handle ,然后从第一个项目的右上角滑动到其右中位置。如果您想拖放一个项目,您将需要多个自定义 CoordinatesProvider
。
RecyclerViewCooperativesProvider
将查找 RecyclerView 中某个项目的坐标:
class RecyclerViewCoordinatesProvider(private val position: Int, private val childItemCoordinatesProvider: CoordinatesProvider) : CoordinatesProvider {
override fun calculateCoordinates(view: View): FloatArray {
return childItemCoordinatesProvider.calculateCoordinates((view as RecyclerView).layoutManager!!.findViewByPosition(position)!!)
}
}
ChildViewCooperativesProvider
将查找具有给定 id 的子项的坐标:
class ChildViewCoordinatesProvider(private val childViewId: Int, private val insideChildViewCoordinatesProvider: CoordinatesProvider) : CoordinatesProvider {
override fun calculateCoordinates(view: View): FloatArray {
return insideChildViewCoordinatesProvider.calculateCoordinates(view.findViewById<View>(childViewId))
}
}
- 最后,我们将创建新的自定义常规位置,它将提供 View 上方和下方的坐标(我假设我们在 LinearLayoutManager 内重新排序):
enum class CustomGeneralLocation : CoordinatesProvider {
UNDER_RIGHT {
override fun calculateCoordinates(view: View): FloatArray {
val screenLocation = IntArray(2)
view.getLocationOnScreen(screenLocation)
return floatArrayOf(screenLocation[0] + view.width - 1f, screenLocation[1] + view.height * 1.5f)
}
},
ABOVE_RIGHT {
override fun calculateCoordinates(view: View): FloatArray {
val screenLocation = IntArray(2)
view.getLocationOnScreen(screenLocation)
return floatArrayOf(screenLocation[0] + view.width - 1f, screenLocation[1] - view.height * 0.5f)
}
}
}
现在,如果您要将项目从
原始位置拖动到
目标位置,其中RecyclerView
的ID为server_list
且拖动 handle 的ID为drag_handle
,使用以下方法:
private fun reorder(from: Int, to: Int) {
onView(withId(R.id.server_list)).perform(GeneralSwipeAction(
Swipe.SLOW,
RecyclerViewCoordinatesProvider(from, ChildViewCoordinatesProvider(R.id.drag_handle, GeneralLocation.CENTER)),
RecyclerViewCoordinatesProvider(to, if (from < to) CustomGeneralLocation.UNDER_RIGHT else CustomGeneralLocation.ABOVE_RIGHT),
Press.FINGER))
}
关于android - 如何使用express编写recyclerview拖放的测试用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54804321/