android drag view smooth

Buda Gavril picture Buda Gavril · Dec 16, 2011 · Viewed 17.6k times · Source

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;
}

Answer

Marylia Gutierrez picture Marylia Gutierrez · Apr 8, 2013

Try to use motionEvent.getRawX() and motionEvent.getRawY() instead of getY and getX