Android 模擬滑動 MotionEvent touch事件

模擬android裏touch事件的滑動,適用於recyclerview等。

通過發送MotionEvent來模擬touch事件,配合ValueAnimator控制滑動的時間,也可以加入差值器等,之所以使用ValueAnimator,是因爲一開始在測試的時候,發現給motion event設置downtime和eventtime根本沒有起效,這兩個time並不是用來控制event觸發的時間,而是要用animator持續發出event纔行。

ValueAnimator anim = ValueAnimator.ofInt(400, 250);
        anim.setDuration(800);
        final MotionEvent event =
                MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, 400, 500, 0);
        view.dispatchTouchEvent(event);
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int x = (int) animation.getAnimatedValue();
                event.setLocation(x, 500);
                event.setAction(MotionEvent.ACTION_MOVE);
                view.dispatchTouchEvent(event);
            }
        });
        anim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                event.setAction(MotionEvent.ACTION_UP);
                view.dispatchTouchEvent(event);
                event.recycle();
            }
        });
        anim.start();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章