Six Methods to Realize Sliding Effect of View by Android

  • 2021-12-12 05:36:04
  • OfStack

In this paper, we share the specific code of Android to realize View sliding effect for your reference. The specific contents are as follows

1. Introduction to Sliding of View

The sliding of View is the basis of Android to realize custom control, and we will inevitably encounter the sliding of View in the development. In fact, no matter which sliding method, the basic idea is similar: when the touch event is transmitted to View, the system records the coordinates of the touch point, and when the finger moves, the system records the coordinates of the moved touch and calculates the offset, and modifies the coordinates of View through the offset.

There are many ways to realize View sliding. This article mainly explains six sliding methods, which are: layout (), offsetLeftAndRight () and offsetTopAndBottom (), LayoutParams, animation, scollTo and scollBy and Scroller; In the next article, we will introduce attribute animation in detail.

2. Six methods to realize View sliding

2.1 layout()

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


public boolean onTouchEvent(MotionEvent event) {
 // Get the abscissa and ordinate at the finger 
 int x = (int) event.getX();
 int y = (int) event.getY();

 switch (event.getAction()) {
  case MotionEvent.ACTION_DOWN:
  lastX = x;
  lastY = y;
  break;

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


case MotionEvent.ACTION_MOVE:
 // Calculate the distance of movement 
 int offsetX = x - lastX;
 int offsetY = y - lastY;
 // Call layout Method to reposition it 
 layout(getLeft()+offsetX, getTop()+offsetY,
  getRight()+offsetX , getBottom()+offsetY);
 break;

Each time we move, we call the layout () method to rearrange ourselves, thus achieving the effect of moving View.

Complete code for customizing View (CustomView. java):


package com.example.liuwangshu.moonviewslide;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

public class CustomView extends View {
 private int lastX;
 private int lastY;

 public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
 super(context, attrs, defStyleAttr);
 }
 public CustomView(Context context, AttributeSet attrs) {
 super(context, attrs);
 }

 public CustomView(Context context) {
 super(context);
 }

 public boolean onTouchEvent(MotionEvent event) {
 // Get the abscissa and ordinate at the finger 
 int x = (int) event.getX();
 int y = (int) event.getY();

 switch (event.getAction()) {
  case MotionEvent.ACTION_DOWN:
  lastX = x;
  lastY = y;
  break;

  case MotionEvent.ACTION_MOVE:
  // Calculate the distance of movement 
  int offsetX = x - lastX;
  int offsetY = y - lastY;
  // Call layout Method to reposition it 
  layout(getLeft()+offsetX, getTop()+offsetY,
   getRight()+offsetX , getBottom()+offsetY);
  break;
 }

 return true;
 }
}

Custom View referenced in layout:


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical">

 <com.example.liuwangshu.moonviewslide.CustomView
 android:id="@+id/customview"
 android:layout_width="80dp"
 android:layout_height="80dp"
 android:layout_margin="50dp"
 android:background="@android:color/holo_red_light" />
</LinearLayout>

2.2 offsetLeftAndRight () vs. offsetTopAndBottom ()

These two methods have the same effect and use as the layout () method. 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;
 // Right left And right Perform migration 
 offsetLeftAndRight(offsetX);
 // Right top And bottom Perform migration 
 offsetTopAndBottom(offsetY);
 break;

2.3 LayoutParams (changing layout parameters)

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


LinearLayout.LayoutParams layoutParams= (LinearLayout.LayoutParams) getLayoutParams();
  layoutParams.leftMargin = getLeft() + offsetX;
  layoutParams.topMargin = getTop() + offsetY;
  setLayoutParams(layoutParams);

Because the parent control is LinearLayout, we use LinearLayout. LayoutParams, and if the parent control is RelativeLayout, we use RelativeLayout. LayoutParams. In addition to using the layout of LayoutParams, we can also implement it with ViewGroup. MarginLayoutParams:


ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) getLayoutParams();
layoutParams.leftMargin = getLeft() + offsetX;
layoutParams.topMargin = getTop() + offsetY;
setLayoutParams(layoutParams);

2.4 Animation

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


<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
 <translate android:fromXDelta="0" android:toXDelta="300" android:duration="1000"/>
</set>

Reference in Java code:


mCustomView.setAnimation(AnimationUtils.loadAnimation(this, R.anim.translate));

Of course, it's easier to move with attribute animation. We have CustomView translated 300 pixels to the right along the X axis in 1000 milliseconds:


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

2.5 scollTo and scollBy

scollTo (x, y) means moving to a specific coordinate point, while scollBy (dx, dy) means moving in increments of dx, dy. Where scollBy will eventually call scollTo. scollTo, scollBy moves the contents of View, and if used in ViewGroup, it moves all its children View. 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;
 // Call layout Method to reposition it 
 layout(getLeft()+offsetX, getTop()+offsetY,
  getRight()+offsetX , getBottom()+offsetY);
 break;
0

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

2.6 Scroller

When we use the scollTo/scollBy method to slide, the process is done instantaneously, so the user experience is not good. Here, we can use Scroller to achieve excessive sliding. This process is not completed instantaneously, but is completed at a fixed time interval. Scroller itself can't realize the sliding of View, it needs to cooperate with computeScroll () method of View to achieve the elastic sliding effect.
Here we realize the smooth right movement of CustomView.

First we initialize Scroller:


case MotionEvent.ACTION_MOVE:
 // Calculate the distance of movement 
 int offsetX = x - lastX;
 int offsetY = y - lastY;
 // Call layout Method to reposition it 
 layout(getLeft()+offsetX, getTop()+offsetY,
  getRight()+offsetX , getBottom()+offsetY);
 break;
1

Next, override the computeScroll () method, This method is called in the draw () method when the View is drawn, In this method, we call the scrollTo () method of the parent class and continuously obtain the current scrolling value through Scroller. Every time we slide a small distance, we call invalidate () method to continuously redraw, and redraw will call computeScroll () method, so that we can achieve the effect of smooth movement by continuously moving a small distance and coherently:


case MotionEvent.ACTION_MOVE:
 // Calculate the distance of movement 
 int offsetX = x - lastX;
 int offsetY = y - lastY;
 // Call layout Method to reposition it 
 layout(getLeft()+offsetX, getTop()+offsetY,
  getRight()+offsetX , getBottom()+offsetY);
 break;
2

Call the Scroller. startScroll () method. We write an smoothScrollTo () method in CustomView, call the Scroller. startScroll () method, and translate delta pixels along the X axis in 2000 milliseconds:


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

Finally, we call the smoothScrollTo () method of CustomView in ViewSlideActivity. java


case MotionEvent.ACTION_MOVE:
 // Calculate the distance of movement 
 int offsetX = x - lastX;
 int offsetY = y - lastY;
 // Call layout Method to reposition it 
 layout(getLeft()+offsetX, getTop()+offsetY,
  getRight()+offsetX , getBottom()+offsetY);
 break;
4

Here we set the CustomView to translate 400 pixels to the right along the X axis.


Related articles: