How to achieve elastic sliding of View in Android-Android development art exploration notes

Source: Internet
Author: User

How to achieve elastic sliding of View in Android-Android development art exploration notes
Introduction

There are many ways to achieve elastic sliding, that is, progressive sliding, but they all share the same idea: A large slide is divided into several small slides and completed within a period of time. This article mainly introduces three kinds of elastic Sliding Modes: Scroller, animation, and Handler.

In this article, "slide" refers to the sliding of the View content rather than the change of the View position.

Example

Click anywhere on the screen. When the finger is in contact with the screen, the text in the screen that triggers ACTION_DOWN will slide PX upwards, and the ACTION_UP text will be triggered to slide PX when the finger leaves the screen.

The basic knowledge supplements the width and coordinate relationship of the View: width = right-left, height = top-bottom. During the translation process, top and left indicate the location information of the original upper left corner, and the value of the View will not change. The four parameters x, y, translationX, and translationY are changed. X is the coordinate of the upper left corner of the View, and translation is the offset of the view relative to the parent container after it is moved. Therefore, x = left + translationX exists. Y works the same. GetX/getY returns the x and y coordinates relative to the upper left corner of the current View, while getRawX/getRawY returns the x and y coordinates relative to the upper left corner of the mobile phone screen. Use Scroller
private void smoothScrollTo(int destX, int destY) {        int scrollX = getScrollX();        int detlaX = destX - scrollX;        int scrollY = getScrollY();        int detlaY = destY - scrollY;        Log.d(TAG, "smoothScrollTo:scrollY, detlaY= " + scrollY+" " + detlaY);        mScroller.startScroll(scrollX, scrollY, detlaX, detlaY, 1000);        invalidate();    }    @Override    public void computeScroll() {        if (mScroller.computeScrollOffset()) {            scrollTo(mScroller.getCurrX(), mScroller.getCurrY());            postInvalidate();        }    }

The above is a typical method of using scroroller to achieve elastic sliding.

The implementation principle is: scroroller itself cannot let the View slide elastically. It needs to be used together with the View computeScroll method to complete this function. Invalidate () is called in the startScroll () method, so that the View is repainted. When the View is repainted, computeScroll () is called in the draw method (), in this method, scrollTo is called to slide to the specified position. Then, redraw the image again using postInvalidate () until the sliding ends.

The following is the source code of the computescroloffset () function. It can be seen that the timePassed standard is used to determine whether the sliding ends.

/**     * Call this when you want to know the new location.  If it returns true,     * the animation is not yet finished.     */     public boolean computeScrollOffset() {        if (mFinished) {            return false;        }        int timePassed = (int)(AnimationUtils.currentAnimationTimeMillis() - mStartTime);        if (timePassed < mDuration) {            switch (mMode) {            case SCROLL_MODE:                final float x = mInterpolator.getInterpolation(timePassed * mDurationReciprocal);                mCurrX = mStartX + Math.round(x * mDeltaX);                mCurrY = mStartY + Math.round(x * mDeltaY);                break;            case FLING_MODE:            ...            ...                break;            }        }        else {            mCurrX = mFinalX;            mCurrY = mFinalY;            mFinished = true;        }        return true;    }
Use Animation
    private static final int FRAME_COUNT = 30;    final int startX = 0;    final int deltaX = 100;    ValueAnimator animator = ValueAnimator.ofInt(0,1).setDuration(1000);    animator.addUpdateListener(new AnimatorUpdateListener() {        @Override        public void onAnimationUpdate(ValueAnimator animator) {            float fraction = animator.getAnimatedFraction();            mButton1.scrollTo(startX + (int) (deltaX * fraction), 0);        }    });    animator.start();

In the above Code, the animation does not act on any object in nature, but completes the entire animation process within Ms. This method scrollTo (startX + (int) (deltaX * fraction), 0) causes the view to slide a little every time the animation is updated.

Use Handler
    private static final int MESSAGE_SCROLL_TO = 1;    private static final int DELAYED_TIME = 33; private Handler mHandler = new Handler() {        public void handleMessage(Message msg) {            switch (msg.what) {            case MESSAGE_SCROLL_TO: {                mCount++;                if (mCount <= FRAME_COUNT) {                    float fraction = mCount / (float) FRAME_COUNT;                    int scrollX = (int) (fraction * 100);                    mButton1.scrollTo(scrollX, 0);                    mHandler.sendEmptyMessageDelayed(MESSAGE_SCROLL_TO, DELAYED_TIME);                }                break;            }            default:                break;            }        };    };

Call the scrollTo method of View to slide some distance in handleMessage of Handler, and then send a Delay message to Handler to slide again. Key Method: mHandler. sendEmptyMessageDelayed (MESSAGE_SCROLL_TO, DELAYED_TIME ).

Source code of the example animation effect

The animation effect in the example is carried out in a TextView, and the text in the TextView is slide. The source code is as follows.

/** * Created by Spark on 2/22/2016 21:12. */public class ElasticText extends TextView {    private static final String TAG = "ElasticText";    private Scroller mScroller;    private VelocityTracker mVelocityTracker;    public ElasticText(Context context) {        super(context);        init();    }    public ElasticText(Context context, AttributeSet attrs) {        super(context, attrs);        init();    }    public ElasticText(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);        init();    }    private void init() {        mScroller = new Scroller(getContext());        mVelocityTracker = VelocityTracker.obtain();    }    @Override    public boolean onTouchEvent(MotionEvent event) {        switch (event.getAction()) {            case MotionEvent.ACTION_DOWN: {                Log.d(TAG, "onTouchEvent: ActionDown");                mScroller.startScroll(getScrollX(), getScrollY(), 0, 400, 600);                invalidate();                break;            }            case MotionEvent.ACTION_MOVE: {                break;            }            case MotionEvent.ACTION_UP: {                Log.d(TAG, "onTouchEvent: ACTION_UP");                mScroller.startScroll(getScrollX(), getScrollY(), 0, -400, 600);                invalidate();                break;            }            default:                break;        }        return true;    }    private void smoothScrollTo(int destX, int destY) {        int scrollX = getScrollX();        int detlaX = destX - scrollX;        int scrollY = getScrollY();        int detlaY = destY - scrollY;        mScroller.startScroll(scrollX, scrollY, detlaX, detlaY, 1000);        invalidate();    }    @Override    public void computeScroll() {        if (mScroller.computeScrollOffset()) {            scrollTo(mScroller.getCurrX(), mScroller.getCurrY());            postInvalidate();        }    }}

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.