SoFunction
Updated on 2025-04-06

Android   Summary of six ways to move View

In Android development, you often encounter a view that requires it to support sliding. The following is a introduction to six ways to move Android view through this article.

layout()

If you pass the coordinates of the sliding target position to layout(), the position of the view will be rearranged, which is visually a sliding effect of the view.

public class DragView extends View{
  private int lastX;
  private int lastY;
  public DragView(Context context, AttributeSet attrs) {
    super(context, attrs);
  }
  public boolean onTouchEvent(MotionEvent event) {
    //Get the horizontal and vertical coordinates at the finger    int x = (int) ();
    int y = (int) ();
    switch(()){
      case MotionEvent.ACTION_DOWN:
        lastX = x;
        lastY = y;
      break;
      case MotionEvent.ACTION_MOVE:
        //Calculate the distance of movement        int offX = x - lastX;
        int offY = y - lastY;
        //Call the layout method to reposition its position        layout(getLeft()+offX, getTop()+offY,
          getRight()+offX  , getBottom()+offY);
      break;
    }
    return true;
  }
} 

offsetLeftAndRight() offsetTopAndBottom()

In fact, these two methods are packages for left and right movements and up and down movements, and what is passed in is the offset.

public boolean onTouchEvent(MotionEvent event) {
    //Get the horizontal and vertical coordinates at the finger    int x = (int) ();
    int y = (int) ();
    switch(()){
      case MotionEvent.ACTION_DOWN:
        lastX = x;
        lastY = y;
      break;
      case MotionEvent.ACTION_MOVE:
        //Calculate the distance of movement        int offX = x - lastX;
        int offY = y - lastY;
        offsetLeftAndRight(offX);
        offsetTopAndBottom(offY);
      break;
    }
    return true;
  } 

LayoutParams

public boolean onTouchEvent(MotionEvent event) {
    //Get the horizontal and vertical coordinates at the finger    int x = (int) ();
    int y = (int) ();
    switch(()){
      case MotionEvent.ACTION_DOWN:
        lastX = x;
        lastY = y;
      break;
      case MotionEvent.ACTION_MOVE:
        //Calculate the distance of movement        int offX = x - lastX;
        int offY = y - lastY;
         mlp = 
            (MarginLayoutParams) getLayoutParams();
         = getLeft()+offX;
         = getTop()+offY;
        setLayoutParams(mlp);
      break;
    }
    return true;
  }

scrollTo() scrollBy()

SceollTo(x,y) should be the end coordinate of the moving

scrollBy(dx,dy) passes in the increment of the movement.

The value passed through scrollBy should be the opposite number of the increment you need!

public boolean onTouchEvent(MotionEvent event) {
    //Get the horizontal and vertical coordinates at the finger    int x = (int) ();
    int y = (int) ();
    switch(()){
      case MotionEvent.ACTION_DOWN:
        lastX = x;
        lastY = y;
      break;
      case MotionEvent.ACTION_MOVE:
        //Calculate the distance of movement        int offX = x - lastX;
        int offY = y - lastY;
        ((View) getParent()).scrollBy(-offX,- offY);
      break;
    }
    return true;
  } 

Scroller

Step 1:

Initialize the Scroller object, i.e. mScroller = new Scroller(context)

Step 2:

Rewrite the computeScroll() method to achieve simulated sliding. You can copy the following last template code:

public void computeScroll() {
  ();
  if(()){
    ((View)getParent()).scrollTo((),());
  }
  invalidate();// Must call} 

Step 3:

Start the simulation process and startScroll method in the appropriate place (usually in move). It has two overloading methods as follows:

startScroll(int startX,int startY, int dx,int dy,int duration)
startScroll(int startX,int startY,int dx,int dy)

What needs to be explained is:

The method is used to determine whether the entire slide has been completed. Returning to true means that it is not completed, otherwise the slide will be completed.

What is obtained by() and getCurrX() are the current sliding coordinates.

3. Finally, the invalidate method must be used to refresh. Because the computeScroll method will not be called automatically, it is called in the draw method. Therefore, you must use invalidate to refresh, and the draw method will be called, and naturally the computeScroll method will be called. This will implement loop calls.

4. In startScroll, the offset is the same as the offset in the scrollBy method, that is, you must also fill in the opposite number of distances you actually want to move. That is, if you actually want it to offset a positive value, fill in its corresponding negative value. If you want to offset a negative value, fill in its corresponding positive value!

public class DragView extends View{
  private int lastX;
  private int lastY;
  private Scroller mScroller;
  public DragView(Context context, AttributeSet attrs) {
    super(context, attrs);
    mScroller = new Scroller(context);
  }
  public boolean onTouchEvent(MotionEvent event) {
    //Get the horizontal and vertical coordinates at the finger    int x = (int) ();
    int y = (int) ();
    switch(()){
      case MotionEvent.ACTION_DOWN:
        lastX = x;
        lastY = y;
      break;
      case MotionEvent.ACTION_MOVE:
        //Calculate the distance of movement        int offX = x - lastX;
        int offY = y - lastY;
        View viewGroup = (View) getParent();
        ((View) getParent()).scrollBy(-offX,- offY);
      break;
    case MotionEvent.ACTION_UP:
      View viewGroup = (View) getParent();
      //Open the slide and return it to the origin      ((),
          (),
          -() ,-());
      break;
    }
    return true;
  }
  public void computeScroll() {
    ();
    if(()) {
      ((View)getParent()).scrollTo((),
            ());
    } 
    invalidate();// Must call  }
}


Here is an introduction to the Android view class

Not a comparison translation, just an understanding translation. This article is for personal review only and does not guarantee the accuracy and correctness of the translation.

A basic concept of a View

1. Basic description:

This class is the basic component of the user interface. View represents a rectangular area on the screen, responsible for drawing this area and handling events.

View is the base class of all widget classes, which are used to create interactive UI widgets (buttons, input boxes, etc.).

The ViewGroup subclass of the View class is the base class of layout. Layout is an invisible container that holds the View (or ViewGroup) and defines the layout attributes of these Views.

It can be said that the View class is the most important class in the user interface class.

2. Use view

2.1 View organization:

The views used in the same window are stored in a tree. You can dynamically add and delete the views through code, or you can also construct the tree by defining a view tree in the XML file.

2.2. Main operations:

2.2.1 Set properties: You can set the properties of the view through the methods of the view and its subclasses, or you can set the properties of the view in the XML file.

2.2.2 Set focus: The requestFocus method can force the view to obtain focus.

2.2.3 Setting listener: You can listen to events of a specific view by setting listener, such as gaining or losing focus, clicking events, etc.

2.2.4 Set visibility: You can hide or display view, setVisability.

2.3. Notes:

Android framework is responsible for measuring laying out and drawing view. Unless you have to implement a ViewGroup by yourself,

Otherwise, the method that implements these functions should not be displayed.

2. Implement custom view

In order to implement a custom view, some standard methods of rewriting some view are required.

The framework will call these methods and think that these methods should be implemented by all views.

These methods do not have to be rewrite all of them. In fact, you can just rewrite the onDraw function.

Three View properties and actions:

1 Attributes:

1.1 IDs: Views has an integer corresponding to, and the id is used to find the specified view in the view number.
You can define a unique ID in the layout file, and call findViewById in the onCreate function of the Activity to find this view.
In the entire tree, the view may not be unique, but when searching within the specified range, we can be sure that it is unique.

2. Location:

The view is a rectangular area. Use the coordinates on the left & as well as the length and width to represent a View. We can use the method getLeft() getTop() getRight() getBottom() getWidth() and other functions

To obtain its location information.