Create a fake drag and drop event to move the ViewPager around

I have ViewPagerwith Fragment. I want to programmatically create a motion event to “peek” at the Fragmentleft and right to the current one Fragmentin ViewPager(showing part of adjacent fragments, and then return to the current one Fragment). It should look like the user did.

I tried ViewPager.fakeDragBy, but it happens instantly and too quickly. I looked at MotionEvent.obtain()and View.dispatchTouchEvent, it's like going for it, right?

Which one Viewdo I need to send to MotionEvents? And I need to manually send a few MotionEventto achieve what I want, for example. ACTION_DOWN, ACTION_???, ACTION_UP?

EDIT :

I tried the following:

public void drag(View view, float fromX, float toX, float fromY,
                 float toY, int stepCount) {

    long downTime = SystemClock.uptimeMillis();
    long eventTime = SystemClock.uptimeMillis();

    float y = fromY;
    float x = fromX;

    float yStep = (toY - fromY) / stepCount;
    float xStep = (toX - fromX) / stepCount;

    MotionEvent event = MotionEvent.obtain(downTime, eventTime,
            MotionEvent.ACTION_DOWN, x, y, 0);

    view.dispatchTouchEvent(event);

    for (int i = 0; i < stepCount; ++i) {

        y += yStep;
        x += xStep;
        eventTime = SystemClock.uptimeMillis();
        event = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_MOVE, x, y, 0);
        view.dispatchTouchEvent(event);

    }

    eventTime = SystemClock.uptimeMillis();
    event = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_UP, x, y, 0);
    view.dispatchTouchEvent(event);

}

What creates the drag and drop movement is just fine, the problem is that it is very fast. I tried Thread.sleep()inside the loop and played with eventTime (adding some time to it at each iteration inside the loop), to no avail: touch events are sent with a delay, but the actual reaction ViewPagerstill happens very quickly.

+4
source share
2 answers

First way :

Use OverScrollerobject c LinearInterpolatorand set the duration (from x1 to x2 in 300 ms)

call computeScrollOffset()inside the for loop to find the current position and break the loop when it isFinished()returns true.


Second way

fakeDrag .

+1

:

if (!viewpager.isFakeDragging()) {
    viewpager.beginFakeDrag();
}
viewpager.fakeDragBy(value);

: fakeDragBy(float), beginFakeDrag(), endFakeDrag().

onAnimationEnd()

@Override
public void onAnimationEnd(Animator mAnimation) {
    viewpager.endFakeDrag();
}
0

All Articles