SoFunction
Updated on 2025-03-11

6 ways to realize View sliding on Android

This article shares with you the specific methods of Android to realize View sliding for your reference. The specific content is as follows

Sliding introduction

View swiping is the basis for Android to implement custom controls. At the same time, we will inevitably encounter View swiping during development. In fact, the basic idea of ​​sliding is similar: when the touch event is transmitted to the View, the system records the coordinates of the touch point, and when the finger moves, the system records the coordinates of the moving touch and calculates the offset, and uses the offset to modify the coordinates of the View.
There are many ways to realize View sliding. This article mainly explains six ways to slide, namely: layout(), offsetLeftAndRight() and offsetTopAndBottom(), LayoutParams, animation, scollTo and scollBy and Scroller; in the next article, we will introduce attribute animation in detail.

2. Six ways to realize view sliding

()

When drawing the view, the onLayout() method will be called to set the display position. Therefore, we can also control the coordinates of the View by modifying the four properties of the View, the left, top, right, and bottom. First, we need to customize a View and get the coordinates of the touch point in the onTouchEvent() method:

public boolean onTouchEvent(MotionEvent event) {
  //Get the horizontal and vertical coordinates at the finger  int X = 0, newX = 0;
  int Y = 0, newY = 0;
  switch (()) {
    case MotionEvent.ACTION_DOWN:
      ("hahahhaha", "Screen position is pressed");
      X = (int) ();
      Y = (int) ();
   
      break;

Next, we calculate the offset in the ACTION_MOVE event, and then call the layout() method to reposition the position of this custom view:

public boolean onTouchEvent(MotionEvent event) {
  //Get the horizontal and vertical coordinates at the finger  int X = 0, newX = 0;
  int Y = 0, newY = 0;
  switch (()) {
    case MotionEvent.ACTION_DOWN:
      ("hahahhaha", "Screen position is pressed");
      X = (int) ();
      Y = (int) ();

      break;
    case MotionEvent.ACTION_MOVE:
      ("hahahhaha", "Screen position is moving");
      newX = (int) ();
      newY = (int) ();
    
      int offsetX = newX - X;
      int offsetY = newY - Y;
      ("hahaha", "offsetX=" + offsetX + ",offsetY=" + offsetY);
      //1. Call the layout method to reposition its position      layout(getLeft()+offsetX, getTop()+offsetY,
          getRight()+offsetX , getBottom()+offsetY);

When we move each time we call the layout() method to re-layout ourselves, thereby achieving the effect of moving the View.

() and offsetTopAndBottom()

These two methods are similar to the layout() method and are used similarly. We replace the code in ACTION_MOVE with the following code:

      case MotionEvent.ACTION_MOVE:
        //Calculate the distance of movement        int offsetX = x - lastX;
        int offsetY = y - lastY;
        //Offer left and right        offsetLeftAndRight(offsetX);
        //Offer the top and bottom        offsetTopAndBottom(offsetY);
        break;

(Change layout parameters)

LayoutParams mainly saves the layout parameters of a View, so we can change the layout parameters of the View through LayoutParams to achieve the effect of changing the position of the View. Similarly, we replace the code in ACTION_MOVE with the following code:

 layoutParams= () getLayoutParams();
  = getLeft() + offsetX;
  = getTop() + offsetY;
 setLayoutParams(layoutParams);

Because the parent control is LinearLayout, we use it, if the parent control is RelativeLayout, we need to use it. In addition to using LayoutParams for layouts, we can also use it to implement:

 layoutParams = () getLayoutParams();
 = getLeft() + offsetX;
 = getTop() + offsetY;
        setLayoutParams(layoutParams);

with scollBy

scollTo(x,y) means moving to a specific coordinate point, while scollBy(dx,dy) means moving increments are dx and dy. Among them, scollBy will eventually call scollTo. scollTo and scollBy move the content of the View. If used in the ViewGroup, it moves all its subViews. We replace the code in ACTION_MOVE with the following code:

((View)getParent()).scrollBy(-offsetX,-offsetY);

To achieve the effect of CustomView moving with our fingers, we need to set the offset to a negative value.


When we use the scollTo/scollBy method to slide, this process is completed instantly, so the user experience is not very good. Here we can use Scroller to achieve excessive sliding. This process is not completed instantly, but is completed at a certain time interval. Scroller itself cannot realize the sliding of the View. It needs to be combined with the ComputeScroll() method of the View to slide elastically.
Here we implement CustomView smoothly to the right.

First we need to initialize the Scroller:

 public CustomView(Context context, AttributeSet attrs) {
    super(context, attrs);
    mScroller = new Scroller(context);
  }

Next, rewrite the computeScroll() method. The system will call the method in the draw() method when drawing the View. In this method, we call the scrollTo() method of the parent class and continuously obtain the current scroll value through the Scroller. For every short distance we slide, we call the invalidate() method to continuously redraw. The computeScroll() method will be called, so that we can achieve the smooth movement effect by constantly moving a small distance and continuing it:

  @Override
  public void computeScroll() {
    ();
    if(()){
      ((View) getParent()).scrollTo((),());
       //Changely call the computeScroll method by constantly redrawing       invalidate();
    } 
  }

Call the() method. We write a smoothScrollTo() method in CustomView, call the() method, and translate delta pixels along the X-axis within 2000 milliseconds:

 public void smoothScrollTo(int destX,int destY){
    int scrollX=getScrollX();
    int delta=destX-scrollX;
    //Slide to destX within 1000 seconds    (scrollX,0,delta,0,2000);
    invalidate();
  }

Finally, we call the smoothScrollTo() method of CustomView in:
//Use Scroll for smooth movement
          (-400,0);
Here we set the CustomView to translate 400 pixels to the right along the X-axis.

6. Animation

You can use View animation to move, create a new anim folder in the res directory and create:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:andro>
  <translate android:fromXDelta="0" android:toXDelta="300" android:duration="1000"/>
</set>

Quote in Java code:

 ((this, ));

Of course, it is easier to move using attribute animation. Let's let CustomView translate 300 pixels along the X-axis in 1000 milliseconds:

(mCustomView,"translationX",0,300).setDuration(1000).start();

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.