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:
firstX
is the first x value that the finger touched on the screensecondX
is the second x value that the finger touched on the screen
(as in, the next time onTouch
was fired with ACTION_MOVE
)latestX
is the most recent x value of the fingersecondLatestX
is the second most recent x value of the fingerAm I calculating the variables incorrectly? I cannot seem to find a logic issue in anything.
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: