Android View system (2) six ways to achieve View sliding

Source: Internet
Author: User
Tags gety

Android View system (2) six ways to achieve View sliding
1. Slide overview of View

View slide is the basis for implementing custom controls in Android, And we will inevitably encounter View slide processing during development. In fact, the basic idea of sliding is similar: When a touch event is uploaded to a View, the system writes down the coordinates of the touch point, when the finger moves, the system records the coordinates of the moved touch, calculates the offset, and uses the offset to modify the coordinates of the View.
There are many ways to achieve View sliding. This article mainly describes six sliding Methods: layout (), offsetLeftAndRight (), and offsetTopAndBottom () layoutParams, animation, scollTo, scollBy, and Scroller. In the next article, we will introduce attribute animation in detail.

2. Six ways to achieve View sliding Layout ()

When the view is drawn, the onLayout () method is called to set the display position, therefore, we can also control the coordinates of a View by modifying the left, top, right, and bottom attributes of the View. First, we need to customize a View and obtain the coordinates of the touch point in the onTouchEvent () method:

Public boolean onTouchEvent (MotionEvent event) {// obtain the x and Y coordinates of 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 will calculate the offset in the ACTION_MOVE event, and then call the layout () method to re-place the location of the custom View:

Case MotionEvent. ACTION_MOVE: // calculate the moving distance. int offsetX = x-lastX; int offsetY = y-lastY; // call the layout method to re-place the moving distance. layout (getLeft () + offsetX, getTop () + offsetY, getRight () + offsetX, getBottom () + offsetY); break;

When we move each time, we call the layout () method to re-layout ourselves to move the View.

All code of the custom 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) {// obtain the x and Y coordinates 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 moving distance. int offsetX = x-lastX; int offsetY = y-lastY; // call the layout method to re-place the moving distance. layout (getLeft () + offsetX, getTop () + offsetY, getRight () + offsetX, getBottom () + offsetY); break;} return true ;}}

Reference custom View in layout:

<code class="hljs xml"><!--{cke_protected}{C}%3C!%2D%2D%3Fxml%20version%3D%221.0%22%20encoding%3D%22utf-8%22%3F%2D%2D%3E--><linearlayout android:layout_height="match_parent" android:layout_width="match_parent" android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">    <com.example.liuwangshu.moonviewslide.customview android:background="@android:color/holo_red_light" android:id="@+id/customview" android:layout_height="80dp" android:layout_margin="50dp" android:layout_width="80dp"></com.example.liuwangshu.moonviewslide.customview></linearlayout></code>
OffsetLeftAndRight () and offsetTopAndBottom ()

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

Case MotionEvent. ACTION_MOVE: // calculate the moving distance from int offsetX = x-lastX; int offsetY = y-lastY; // offset offsetLeftAndRight (offsetX) to left and right ); // offset offsetTopAndBottom (offsetY) to top and bottom; break;
LayoutParams (Change layout parameters)

LayoutParams stores a layout parameter of the View. Therefore, we can use LayoutParams to change the layout parameter of the View so as to change the position of the 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. If the parent control is RelativeLayout, RelativeLayout. LayoutParams is used. In addition to LayoutParams of the layout, we can also use ViewGroup. MarginLayoutParams to implement:

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

You can use the View animation to move the file. In the res directory, create an anim folder and create translate. xml:

<code class="hljs xml"><!--{cke_protected}{C}%3C!%2D%2D%3Fxml%20version%3D%221.0%22%20encoding%3D%22utf-8%22%3F%2D%2D%3E--><set xmlns:android="http://schemas.android.com/apk/res/android">    <translate android:duration="1000" android:fromxdelta="0" android:toxdelta="300"></translate></set></code>

Reference in Java code:

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

Of course, it is easier to use property animation to move the CustomView along the X axis in 1000 milliseconds and then right-shift 300 pixels:

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

ScollTo (x, y) indicates moving to a specific coordinate point, while scollBy (dx, dy) indicates moving increment to dx and dy. ScollBy also calls scollTo. ScollTo and scollBy move the View content. If they are used in the ViewGroup, they move all their child views. We replace the code in ACTION_MOVE with the following code:

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

To achieve CustomView as our fingers move, we need to set the offset to a negative value.

Scroller

When we use the scollTo/scollBy method to slide, this process is completed instantly, so the user experience is not good. Here we can use scroroller to implement the current excessive sliding effect. This process is not completed in an instant, but completed at a certain interval. Scroroller itself cannot achieve the sliding of the View. It must work with the computeScroll () method of the View to achieve the sliding effect.
Here, we implement smooth mview movement to the right.

First, we need to initialize Scroller:
  public CustomView(Context context, AttributeSet attrs) {        super(context, attrs);        mScroller = new Scroller(context);    }
Next, rewrite the computeScroll () method. The system will call this method in the draw () method when drawing the View. In this method, we call scrollTo () of the parent class () method and get the current rolling value through Scroller. Every short sliding distance, we call the invalidate () method to re-paint continuously. The re-painting will call the computeScroll () method, in this way, we can achieve smooth movement by constantly moving a small distance and coherent:
@ Override public void computeScroll () {super. computeScroll (); if (mScroller. computescroloffset () {(View) getParent ()). scrollTo (mScroller. getCurrX (), mScroller. getCurrY ();} // call the computeScroll method invalidate () through continuous re-painting ();}
Call Scroller. startScroll. In CustomView, we write an smoothScrollTo () method, call scroler. startScroll () method, and translate the delta pixel along the X axis within 2000 milliseconds:
Public void smoothScrollTo (int destX, int destY) {int scrollX = getScrollX (); int delta = destX-scrollX; // slide to destX mscroroller within 1000 seconds. startScroll (scrollX, 0, delta,); invalidate ();}
Finally, we call the smoothScrollTo () method of CustomView in ViewSlideActivity. java:
// Use Scroll to smoothly move mCustomView. smoothScrollTo );

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

Download github source code

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.