Android TouchEvent修改

时间:2013-08-29 07:38:45

标签: android android-viewpager android-animation

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

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

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

2 个答案:

答案 0 :(得分:2)

我终于做到了。

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;
};

答案 1 :(得分:-1)

对于有同样问题并使用 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