gpt4 book ai didi

Android:以编程方式创建滑动手势事件

转载 作者:行者123 更新时间:2023-12-03 17:43:20 72 4
gpt4 key购买 nike

我一直试图在谷歌上找到这个特定案例的答案,但令人惊讶的是在任何地方都找不到它(只有关于检测而不是创建滑动的答案)。我想在屏幕上实际“运行”一个从右到左的模拟滑动(不管在哪里,但最好是从右边缘到左)。我尝试过这样的事情,但我得到了一个 NPE:

final float viewWidth = view.getWidth();
TouchUtils.drag(null,viewWidth,1f,0f,0f,1);

原因?我需要在没有真正引用页面位置的无限 View 页面中强制滑动到下一页(所以我不能只使用 setCurrentItem)。

有任何想法吗?

最佳答案

如前所述TouchUtils.drag使用 Instrumentation可用于 androidTest只要。
我编写了不需要 Instrumentation 的扩展函数,因此它们可以在发布版本中使用:

fun ViewGroup.performSwipeToLeft(target: View) {
this.performSwipe(target, distanceX = -this.width * .5f, distanceY = 0f)
}
fun ViewGroup.performSwipeToRight(target: View) {
this.performSwipe(target, distanceX = +this.width * .5f, distanceY = 0f)
}
fun ViewGroup.performSwipeToTop(target: View) {
this.performSwipe(target, distanceX = 0f, distanceY = -this.height * .5f)
}
fun ViewGroup.performSwipeToBottom(target: View) {
this.performSwipe(target, distanceX = 0f, distanceY = +this.width * .5f)
}

fun ViewGroup.performSwipe(target: View, distanceX: Float, distanceY: Float) {
val parentCoords = intArrayOf(0, 0)
this.getLocationInWindow(parentCoords)

val childCoords = intArrayOf(0, 0)
target.getLocationInWindow(childCoords)

val initGlobalX = childCoords[0].toFloat() + 1f
val initGlobalY = childCoords[1].toFloat() + 1f

val initLocalX = (childCoords[0] - parentCoords[0]).toFloat() + 1f
val initLocalY = (childCoords[1] - parentCoords[1]).toFloat() + 1f

val downTime = SystemClock.uptimeMillis()
var eventTime = SystemClock.uptimeMillis()

this.dispatchTouchEvent(
MotionEvent.obtain(
downTime,
eventTime,
MotionEvent.ACTION_DOWN,
initGlobalX,
initGlobalY,
0
).apply {
setLocation(initLocalX, initLocalY)
source = InputDevice.SOURCE_TOUCHSCREEN
}
)

val steps = 20
var i = 0
while (i in 0..steps) {
val globalX = initGlobalX + i * distanceX / steps
val globalY = initGlobalY + i * distanceY / steps
val localX = initLocalX + i * distanceX / steps
val localY = initLocalY + i * distanceY / steps
if (globalX <= 10f || globalY <= 10f) {
break
}
this.dispatchTouchEvent(
MotionEvent.obtain(
downTime,
++eventTime,
MotionEvent.ACTION_MOVE,
globalX,
globalY,
0
).apply {
setLocation(localX, localY)
source = InputDevice.SOURCE_TOUCHSCREEN
}
)
i++
}

this.dispatchTouchEvent(
MotionEvent.obtain(
downTime,
++eventTime,
MotionEvent.ACTION_UP,
initGlobalX + i * distanceX,
initGlobalY + i * distanceY,
0
).apply {
setLocation(initLocalX + i * distanceX, initLocalY + i * distanceY)
source = InputDevice.SOURCE_TOUCHSCREEN
}
)
}
要使用它,您需要将当前页面内容作为参数传递,并将 viewPager 作为此函数的接收者:
val viewPager = ...
viewPager.performSwipeToLeft(viewPager.getChildAt(viewPager.currentItem))

关于Android:以编程方式创建滑动手势事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30563169/

72 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com