I have to drag some views on screen. I am modifying their position by changing left and top of their layout parameters from motion event on ACTION_MOVE from touch listener. Is there a way to "drag" items more smooth? Because tis kind of "dragging" is no smooth at all... Here is the code
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
dx = (int) motionEvent.getX();
dy = (int) motionEvent.getY();
break;
case MotionEvent.ACTION_MOVE:
int x = (int) motionEvent.getX();
int y = (int) motionEvent.getY();
RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) view.getLayoutParams();
int left = lp.leftMargin + (x - dx);
int top = lp.topMargin + (y - dy);
lp.leftMargin = left;
lp.topMargin = top;
view.setLayoutParams(lp);
break;
}
return true;
}
Try to use motionEvent.getRawX() and motionEvent.getRawY() instead of getY and getX
You need not to use LayoutParameters to drag. You can do it by just setting the X and Y coordinates of the view. You can read more on this here.
You can do something like this.
@Override
public boolean onTouch(View view, MotionEvent event) {
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
dX = view.getX() - event.getRawX();
dY = view.getY() - event.getRawY();
break;
case MotionEvent.ACTION_MOVE:
view.setY(event.getRawY() + dY);
view.setX(event.getRawX() + dX);
break;
default:
return false;
}
return true;
}
The reason of non-smooth move is integer value of leftMargin and topMargin.
For smooth move position should be float.
This could help.
It would be useful to see how you are processing your ACTION_MOVE events. Are you utilizing all the points using event.getHistorical() method? If that does not give you a smoother drag, other idea might be to interpolate points on the path. I believe there will be a trade-off between achieving smoothness of movement and quick response to user's touch. HTH.
You should round your ints, also using margins is not going to be very smooth, use a different layout and set X and Y coordinates according to screen dimensions.
来源:https://stackoverflow.com/questions/8535599/android-drag-view-smooth