Sliding view in Android

Time:2021-12-2

In life, we often see some dazzling dynamic interfaces when using Android apps. Many of these effects are due to the sliding of view, such as the sliding of recyclerview. We can also make such effects by mastering the sliding mode of view; There are four common methods to realize view sliding: using scrollto / scrollby, using animation, changing layout parameters and using layout. They will be introduced one by one below.

1. Use scrollto / scrollby
View provides scrollto (int x, int y) and scrollby (int x, int y) to realize its sliding. The specific implementation code (based on Android API 27) is as follows:

public void scrollTo(int x, int y) {
  if (mScrollX != x || mScrollY != y) {
    int oldX = mScrollX;
    int oldY = mScrollY;
    mScrollX = x;
    mScrollY = y;
    invalidateParentCaches();
    onScrollChanged(mScrollX, mScrollY, oldX, oldY);
    if (!awakenScrollBars()) {
        postInvalidateOnAnimation();
    }
   }
 }

public void scrollBy(int x, int y) {
  scrollTo(mScrollX + x, mScrollY + y);
}

From the two methods of scrollto (int x, int y) and scrollby (int x, int y), it is concluded that scrollto (int x, int y) realizes the absolute sliding of the passed parameters, while scrollby (int x, int y) realizes the relative sliding of the current position because it calls the scrollto (int x, int y) method. In these two methods, there are two member variables, mscollx and mscolly, where mscollx represents the horizontal distance between the left edge of view and the left edge of view content, and mscolly represents the vertical distance between the upper edge of view and the upper edge of view content. Next, write an example to use the scrollby (int x, int y) method; First, create a new layout file activity_ view_ general_ Slide.xml. Its code is as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout        xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.administrator.androidart.activites.ViewGeneralSlideActivity">
<TextView
 android:id="@+id/tv_scroll"
 android:layout_width="match_parent"
 android:layout_marginTop="20px"
 Android: text = "scrollby sliding"
 android:background="#00FF00"
 android:onClick="onClickView"
 android:gravity="bottom"
 android:layout_height="match_parent" />

</LinearLayout>

Then create a new Java file named viewgeneralslideactivity. The code is as follows:

private TextView mTv;
private MyHandler mHandler = null;
private int mSlideY = 20;
private int mSlideX = 20;
private MyThread thread = null;
private boolean isRunThread = true;

class MyHandler extends Handler {
   @Override
   public void handleMessage(Message msg) {
      super.handleMessage(msg);
      mTv.scrollBy(0,mSlideY);
      mSlideY += 10;
   }
 }
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_view_general_slide);
    mTv = findViewById(R.id.tv_scroll);
    mHandler = new MyHandler();
    thread = new MyThread();
}
public void onClickView(View view) {
    thread.start();
}
class MyThread extends Thread {
    @Override
    public void run() {
        super.run();
        while (isRunThread) {
           try {
               Thread.sleep(500);
               sendMessage();
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
        }
      }
  }
@Override
protected void onDestroy() {
     super.onDestroy();
     isRunThread = false;
     if (mHandler != null) {
          mHandler.removeCallbacksAndMessages(null);
     }
 }
 
 private void sendMessage() {
     Message message = Message.obtain();
     mHandler.sendMessage(message);
 }
 

The effect before clicking the “scrollby” control is as follows:
Sliding view in Android

After clicking the “scrollby” control, the effect is as follows:
Sliding view in Android

Note: whether it is the scrollby (int x, int y) or scrollto (int x, int y) method, the sliding is not the view itself, but the content of the view.

2. Use animation

Using animation to move the view is realized through the two attributes of view translationx and translationy. It can use either traditional view animation or attribute animation; In terms of using attribute animation, if you want to use it in Android version 3.0 or below, you need to use the open source animation library nineoldandroids, whose official address is:http://nineoldandroids.com/。 The following example is implemented in code, using view animation to move.

2. 1 using traditional view animation

(1) Create a new anim folder in the res directory and create a view under the anim folder_ translate.xml:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true"
android:zAdjustment="normal">
   <translate android:fromXDelta="0"
   android:fromYDelta="0"
   android:toXDelta="200"
   android:toYDelta="200"
   android:duration="3000"
   />
</set>
 

(2) Create a new Java file named animationactivity and the code to implement it, as shown below:

private TextView mTv;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_animation);
    mTv = findViewById(R.id.tv);
}
public void onClick(View view) {
    Animation animation = AnimationUtils.loadAnimation(this, R.anim.view_translate);
    mTv.startAnimation(animation);
}

(3) Create a new activity under the layout folder_ The code of the animation.xml file is as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical"
 tools:context="demo1.xe.com.myapplication2.AnimationActivity">
     <Button android:layout_width="match_parent"
     Android: text = "click this button to move the view"
     android:onClick="onClick"
     android:layout_height="wrap_content" />
     <TextView android:id="@+id/tv"
     android:layout_width="300px"
     android:gravity="center"
     Android: text = "mobile traditional view"
     android:background="#FF0000"
     android:layout_height="wrap_content" />
</LinearLayout>

Before clicking the button “click this button to move view”, the effect diagram of its operation is as follows:

Sliding view in Android

After clicking the button “click this button to move the view”, the effect diagram of a moment during its movement is as follows:

Sliding view in Android

2. 2 move using attribute animation

(1) In order to be compatible with phones with Android versions below 3.0, add the dependency of nineoldandroids in the build.gradle file in the project app Directory:

implementation 'com.nineoldandroids:library:2.4.0'

(2) Create a new Java file named animation2activity. Its code is as follows:

private TextView mTv;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_animation2);
    mTv = findViewById(R.id.tv);
}
public void onClick(View view) {
    ObjectAnimator.ofFloat(mTv,"translationY",0,300).setDuration(1000).start();
}

public void onClick2(View view) {
    Toast. Maketext (this, "click" movable attribute view ", toast. Length_short). Show();
}

(3) Create a new activity under the layout folder_ The code of the animation2.xml file is as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical"
 tools:context="demo1.xe.com.myapplication2.AnimationActivity">
     <Button android:layout_width="match_parent"
         Android: text = "click this button to move the view of attribute animation"
         android:onClick="onClick"
         android:layout_height="wrap_content" />
     <TextView android:id="@+id/tv"
         android:layout_width="300px"
         android:gravity="center"
         Android: text = "movable attribute view"
         android:background="#FF0000"
         android:onClick="onClick2"
         android:layout_height="wrap_content" />
</LinearLayout>

Before clicking “click this button to move the view of attribute animation”, its operation effect is as follows:

Sliding view in Android

After clicking the button “click this button to move the view of attribute animation”, the effect diagram of a moment during its movement is as follows:

Sliding view in Android

The above examples of using animation are summarized as follows:(1) The traditional view animation only moves the image, not really changes the position of the view. Its fillafter attribute defaults to false, which is equivalent to returning to the original position after the animation; When the fillafter property is set to true, the image will not return to its original position after the view completes the animation. However, if you do an event monitoring in the view, clicking the view after the animation will not respond to the event. Clicking the original position of the view will respond to the event, because in the eyes of the system, the position of the view has not changed after the animation. (2) Attribute animation cannot be used on mobile phones below Android version 3.0. To use it, you must add nineoldandroids; Attribute animation does not move the image, but really changes the position of the view. If you do an event monitoring in the view, clicking the original position of the view will not have an event response, and clicking the position after the animation will have an event response.

3. Change layout parameters

There are two ideas to realize view sliding by changing layout parameters: (1) to move a view to the right, you only need to increase its marginleft parameter and move it to other directions. Similarly, you only need to change the corresponding margin parameter; (2) A view is placed in advance next to the view to be moved, and its initialization width is 0. Then, to move the view to the right, just increase the width of the pre placed view, so as to “push” the view to the right. Examples are as follows:

(1) Create a new layout file called activity_ change_ layout_ parameter.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical"
 tools:context="demo1.xe.com.myapplication2.ChangeLayoutParameterActivity">
     <Button android:layout_width="match_parent"
         Android: text = "click me to move the first view"
         android:onClick="onClick"
         android:layout_height="wrap_content" />
     <Button android:layout_width="match_parent"
         Android: text = "click me to move the second view"
         android:onClick="onClick2"
         android:layout_height="wrap_content" />
     <TextView android:id="@+id/tv"
         android:layout_width="350px"
         android:onClick="onClick3"
         Android: text = "mobile view by changing layout parameters"
         android:layout_height="wrap_content" />
     <LinearLayout android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:orientation="horizontal">
         <View android:id="@+id/view"
             android:layout_width="0px"
             android:layout_height="1px"/>
         <TextView android:id="@+id/tv2"
             android:layout_width="350px"
             android:onClick="onClick4"
             Android: text = "mobile view by changing layout parameters"
             android:layout_height="wrap_content" />
     </LinearLayout>
 </LinearLayout>

Create a new Java file named changelayoutparameteractivity. Its code is as follows:

TextView mTv;
View mView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_change_layout_parameter);
    mTv = findViewById(R.id.tv);
    mView = findViewById(R.id.view);
}
public void onClick(View view) {
    ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) mTv.getLayoutParams();
    params.leftMargin += 200;
    params.width += 200;
    mTv.requestLayout();
}
public void onClick2(View view) {
    ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) mView.getLayoutParams();
    params.width += 200;
    mView.requestLayout();
}
public void onClick3(View view) {
    Toast. Maketext (this, "click the first view that can be moved by changing layout parameters", toast. Length_short). Show();
}
public void onClick4(View view) {
    Toast. Maketext (this, "click the second view that can be moved by changing layout parameters", toast. Length_short). Show();
}

Before clicking the “click I can move the first view” button, the effect diagram is as follows:

Sliding view in Android

After clicking the “click I can move the first view” button, the effect diagram is as follows:

Sliding view in Android

Summarize the above changes in layout parameters and mobile view:Whether you increase the marginleft parameter of view; Or put a view next to the view to be moved in advance, and then move the view to the right; Both of them realize the movement of the real position of view, rather than the movement of view image; If event listening is performed in the mobile view, clicking the original location will not respond to the event, and clicking the moved location will respond to the event.

4. Using layout

The idea of using layout to move the view is as follows: record the coordinates in motionevent in the ontouchevent method of view, record when pressed, calculate their offset when moving, and call layout() to redraw the position of the view; Here is an example:

(1) Create a new layout file called activity_ use_ layout.xml :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 tools:context="demo1.xe.com.myapplication2.UseLayoutActivity">
     <TextView android:id="@+id/tv"
         android:layout_width="wrap_content"
         Android: text = "use layout to move view"
         android:onClick="onClick"
         android:layout_height="wrap_content" />
</RelativeLayout>

(2) Create a new Java file named uselayoutactivity. Its implementation code is as follows:

TextView mTv;
private int lastX,lastY;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_use_layout);
    mTv = findViewById(R.id.tv);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
    int x = (int) event.getRawX();
    int y = (int) event.getRawY();
    switch (event.getAction()){
        case MotionEvent.ACTION_DOWN:
            lastX = x;
            lastY = y;
            break; 
         case MotionEvent.ACTION_MOVE:
            int offsetX = x - lastX;
            int offsetY = y - lastY;
            mTv.layout(mTv.getLeft()+offsetX,
            mTv.getTop()+offsetY,
            mTv.getRight()+offsetX,
            mTv.getBottom()+offsetY);
            lastX = x;
            lastY = y;
            break;
     }
    return true;
}
public void onClick(View v){
    Toast. Maketext (this, "click" use layout to move view ", toast. Length_short). Show();
}

The effect picture before sliding the screen is as follows:

Sliding view in Android

The effect diagram of a moment when sliding the screen is as follows:

Sliding view in Android

Summarize the above mobile view using layout:When you use layout to move a view, you change not the image of the view, but the real position of the view. Therefore, if you want to set the event listening of the view, click the moved view to respond to the event; Using layout to move the view is combined with the touch event of activity. When touching, obtain the X and Y coordinates relative to the touch on the screen, and then calculate the moving distance during the finger movement, plus the position of the view relative to the parent view to obtain the position of the view after moving. Finally, the view uses the layout method to re layout and re paint.

Well, this article ends here. Due to my limited technical level, it is inevitable that there will be mistakes. Welcome criticism and correction. Thank you for reading. AttachedAndroid View Slide demo

Sliding view in AndroidFocus on WeChat official account and read more interesting technical articles.