androidandroid-viewontouchlistenermotioneventontouch

View not moving with finger with onTouchListener


I'm trying to make a View's x value move along with a finger as it drags across the screen. Although the view moving is smooth, it only moves ~1/3 of the distance that the finger does. The View in my case happens to be a RecyclerView, but I think this is irrelevant to the problem. What am I doing wrong in the following implementation?

view.setOnTouchListener((v, event) -> {
        switch (event.getActionMasked()) {
            case MotionEvent.ACTION_UP:
                view.animate().translationX(0).setDuration(200);
                break;
            case MotionEvent.ACTION_MOVE:
                if (event.getHistorySize() < 1) break;
                final float latestX = event.getX(),
                        secondLatestX = event.getHistoricalX(event.getHistorySize() - 1),
                        firstX = event.getHistoricalX(0),
                        secondX = (event.getHistorySize() > 1) ?
                                event.getHistoricalX(1) : latestX;
                final float firstY = event.getHistoricalY(0),
                        secondY = (event.getHistorySize() > 1) ?
                                event.getHistoricalY(1) : event.getY();
                // if initial change x is greater than y
                if (Math.abs(secondX - firstX) > Math.abs(secondY - firstY)) {
                    view.setX(messageList.getX() + (latestX - secondLatestX));
                    return true;
                }
                break;
        }
        return false;
    });

If the code needs some explanation:

Am I calculating the variables incorrectly? I cannot seem to find a logic issue in anything.


Solution

  • Since I could not find any way to do this, I just decided to create my own library from the ground up. Here it is:

    https://github.com/GregoryConrad/SlideDetector