2

我正在使用 ViewPager 尝试完成一些动画。其中之一是尝试从左向右滑动(视图寻呼机的默认转换是从右向左)。我已经做到了。

我的问题是我想“破解”触摸事件,所以我不需要修改视图寻呼机。例如,对于从左到右的转换,我将希望在传递给视图分页器的触摸事件中使用 X 进行某种镜像。

@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
    event.setX(Math.abs(event.getX() - getWidth());
    return super.onInterceptTouchEvent(event);
}
4

2 回答 2

5

我终于做到了。

public boolean dispatchTouchEvent(MotionEvent event) {
    MotionEvent hackedEvent = MotionEvent.obtain(event.getDownTime(),
            event.getEventTime(), event.getAction(), (event.getX() - getWidth()) * -1,
            event.getY(), event.getMetaState());
    boolean result = super.dispatchTouchEvent(hackedEvent);
    hackedEvent.recycle();
    return result;
};
于 2013-08-29T08:40:48.977 回答
0

对于有同样问题并使用 Kotlin 的人:

我创建了一个扩展函数来以数据类样式复制整个 MotionEvent,它允许您修改它的某些属性。

例如

val modifiedEvent = event.copy(downTime = System.currentTimeMillis())
event.recycle()

扩展功能:

/**
 * Copies a whole MotionEvent. Use the named parameters to modify certain 
values.
 * Don't forget to recycle the original event (if it is not used anymore :) 
)!
 */
fun MotionEvent.copy(
    downTime: Long = getDownTime(),
    eventTime: Long = getEventTime(),
    action: Int = getAction(),
    pointerCount: Int = getPointerCount(),
    pointerProperties: Array<MotionEvent.PointerProperties>? =
        (0 until getPointerCount())
            .map { index ->
                MotionEvent.PointerProperties().also { pointerProperties ->
                    getPointerProperties(index, pointerProperties)
                }
            }
            .toTypedArray(),
    pointerCoords: Array<MotionEvent.PointerCoords>? =
        (0 until getPointerCount())
            .map { index ->
                MotionEvent.PointerCoords().also { pointerCoords ->
                    getPointerCoords(index, pointerCoords)
                }
            }
            .toTypedArray(),
    metaState: Int = getMetaState(),
    buttonState: Int = getButtonState(),
    xPrecision: Float = getXPrecision(),
    yPrecision: Float = getYPrecision(),
    deviceId: Int = getDeviceId(),
    edgeFlags: Int = getEdgeFlags(),
    source: Int = getSource(),
    flags: Int = getFlags()
): MotionEvent =
    MotionEvent.obtain(
        downTime,
        eventTime,
        action,
        pointerCount,
        pointerProperties,
        pointerCoords,
        metaState,
        buttonState,
        xPrecision,
        yPrecision,
        deviceId,
        edgeFlags,
        source,
        flags
    )

来源:https ://gist.github.com/sebschaef/b803da53217c88e8c691aeed08602193

于 2021-01-03T17:24:38.907 回答