SoFunction
Updated on 2025-03-11

Android realizes the effect of view drag and drop following finger movement

Today I want to implement this function, but searching for codes online is all achieved using setPadding, setMargin and other methods. This was fine before Android 4.0, but after Android 4.0, the system has provided a simpler method for us to use, that is,setTranslationX() andsetTranslationY() . These two are the property methods of the View. Now I use these two methods to achieve the effect of a View that can be dragged and moved with your fingers. The code is very, very simple:

public class DragView extends TextView { 
  float moveX; 
  float moveY; 
  public DragView(Context context) { 
    super(context); 
  } 
  public DragView(Context context, AttributeSet attrs) { 
    super(context, attrs); 
  } 
  @Override 
  public boolean onTouchEvent(MotionEvent event) { 
    switch (()) { 
      case MotionEvent.ACTION_DOWN: 
        moveX = (); 
        moveY = (); 
        break; 
      case MotionEvent.ACTION_MOVE: 
        setTranslationX(getX() + (() - moveX)); 
        setTranslationY(getY() + (() - moveY)); 
        break; 
      case MotionEvent.ACTION_UP: 
        break; 
      case MotionEvent.ACTION_CANCEL: 
        break; 
    } 
    return true; 
  } 
} 

Summarize

The above is what the editor introduces to you to realize the effect of view drag and drop and move with your fingers. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!