Android 阻尼回彈效果簡單實現(xiàn)(類似iOS)

一、普通控件帶阻尼回彈效果;

先上圖:


普通控件阻尼回彈效果.gif

再上代碼:

/**
 * ================================
 * Des: 阻尼回彈 DampingReboundFrameLayout
 * Created by kele on 2021/2/22.
 * E-mail:984127585@qq.com
 * ================================
 */
public class DampingReboundFrameLayout extends FrameLayout {

    private View mPrinceView;// 太子View
    private int mInitTop, mInitBottom, mInitLeft, mInitRight;// 太子View初始時上下坐標(biāo)位置(相對父View,
    // 即當(dāng)前ReboundEffectsView)
    private boolean isEndwiseSlide;// 是否縱向滑動
    private float mVariableY;// 手指上下滑動Y坐標(biāo)變化前的Y坐標(biāo)值
    private float mVariableX;// 手指上下滑動X坐標(biāo)變化前的X坐標(biāo)值

    private int orientation;//1:豎向滾動 2:橫向滾動

    public DampingReboundFrameLayout(Context context) {
        this(context, null);
    }

    public DampingReboundFrameLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public DampingReboundFrameLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.setClickable(true);
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.DampingReboundFrameLayout);
        orientation = ta.getInt(R.styleable.DampingReboundFrameLayout_orientation, 1);
        ta.recycle();
    }

    /**
     * Touch事件
     */
    @Override
    public boolean onTouchEvent(MotionEvent e) {
        if (null != mPrinceView) {
            switch (e.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    onActionDown(e);
                    break;
                case MotionEvent.ACTION_MOVE:
                    return onActionMove(e);
                case MotionEvent.ACTION_UP:
                case MotionEvent.ACTION_CANCEL:
                    onActionUp(e);// 當(dāng)ACTION_UP一樣處理
                    break;
            }
        }
        return super.onTouchEvent(e);
    }

    /**
     * 手指按下事件
     */
    private void onActionDown(MotionEvent e) {
        mVariableY = e.getY();
        mVariableX = e.getX();
        /**
         * 保存mPrinceView的初始上下高度位置
         */
        mInitTop = mPrinceView.getTop();
        mInitBottom = mPrinceView.getBottom();
        mInitLeft = mPrinceView.getLeft();
        mInitRight = mPrinceView.getRight();
    }

    /**
     * 手指滑動事件
     */
    private boolean onActionMove(MotionEvent e) {
        float nowY = e.getY();
        float diffY = (nowY - mVariableY) / 2;
        if (orientation == 1 && Math.abs(diffY) > 0) {// 上下滑動
            // 移動太子View的上下位置
            mPrinceView.layout(mPrinceView.getLeft(), mPrinceView.getTop() + (int) diffY,
                    mPrinceView.getRight(), mPrinceView.getBottom() + (int) diffY);
            mVariableY = nowY;
            isEndwiseSlide = true;
            return true;// 消費(fèi)touch事件
        }

        float nowX = e.getX();
        float diffX = (nowX - mVariableX) / 5;//除數(shù)越大可以滑動的距離越短
        if (orientation == 2 && Math.abs(diffX) > 0) {// 左右滑動
            // 移動太子View的左右位置
            mPrinceView.layout(mPrinceView.getLeft() + (int) diffX, mPrinceView.getTop(),
                    mPrinceView.getRight() + (int) diffX, mPrinceView.getBottom());
            mVariableX = nowX;
            isEndwiseSlide = true;
            return true;// 消費(fèi)touch事件
        }
        return super.onTouchEvent(e);
    }

    /**
     * 手指釋放事件
     */
    private void onActionUp(MotionEvent e) {
        if (isEndwiseSlide) {// 是否為縱向滑動事件
            // 是縱向滑動事件,需要給太子View重置位置
            if (orientation==1){
                resetPrinceViewV();
            }else if (orientation==2){
                resetPrinceViewH();
            }
            isEndwiseSlide = false;
        }
    }

    /**
     * 回彈,重置太子View初始的位置
     */
    private void resetPrinceViewV() {
        TranslateAnimation ta = new TranslateAnimation(0, 0, mPrinceView.getTop() - mInitTop, 0);
        ta.setDuration(600);
        mPrinceView.startAnimation(ta);
        mPrinceView.layout(mPrinceView.getLeft(), mInitTop, mPrinceView.getRight(), mInitBottom);
    }

    private void resetPrinceViewH() {
        TranslateAnimation ta = new TranslateAnimation(mPrinceView.getLeft() - mInitLeft, 0, 0, 0);
        ta.setDuration(600);
        mPrinceView.startAnimation(ta);
        mPrinceView.layout(mInitLeft, mPrinceView.getTop(), mInitRight, mPrinceView.getBottom());
    }

    /**
     * XML布局完成加載
     */
    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        if (getChildCount() > 0) {
            mPrinceView = getChildAt(0);// 獲得子View,太子View
        }
    }
}

res-values-attr.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="DampingReboundFrameLayout">
        <attr name="orientation">
            <enum name="portrait" value="1" />
            <enum name="landscape" value="2" />
        </attr>
    </declare-styleable>
</resources>
二、NestesScrollView帶阻尼回彈效果:

先上圖:


NestedScrollView阻尼回彈效果.gif

再上代碼:

/**
 * ================================
 * Des: 阻尼回彈 DampingReboundNestedScrollView
 * Created by kele on 2021/2/22.
 * E-mail:984127585@qq.com
 * ================================
 */
public class DampingReboundNestedScrollView extends NestedScrollView {

    // y方向上當(dāng)前觸摸點(diǎn)的前一次記錄位置
    private int previousY = 0;
    // y方向上的觸摸點(diǎn)的起始記錄位置
    private int startY = 0;
    // y方向上的觸摸點(diǎn)當(dāng)前記錄位置
    private int currentY = 0;
    // y方向上兩次移動間移動的相對距離
    private int deltaY = 0;

    // 第一個子視圖
    private View childView;

    // 用于記錄childView的初始位置
    private Rect topRect = new Rect();

    //水平移動搞定距離
    private float moveHeight;

    public DampingReboundNestedScrollView(Context context) {
        this(context,null);

    }

    public DampingReboundNestedScrollView(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public DampingReboundNestedScrollView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setFillViewport(true);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        if (getChildCount() > 0) {
            childView = getChildAt(0);
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        if (null == childView) {
            return super.dispatchTouchEvent(event);
        }

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                startY = (int) event.getY();
                previousY = startY;

                // 記錄childView的初始位置
                topRect.set(childView.getLeft(), childView.getTop(),
                        childView.getRight(), childView.getBottom());
                moveHeight = 0;
                break;
            case MotionEvent.ACTION_MOVE:
                currentY = (int) event.getY();
                deltaY = currentY - previousY;
                previousY = currentY;

                //判定是否在頂部或者滑到了底部
                if((!childView.canScrollVertically(-1)&&(currentY-startY)>0)||(!childView.canScrollVertically(1)&&(currentY-startY)<0)){
                    //計算阻尼
                    float distance = currentY - startY;
                    if (distance < 0) {
                        distance *= -1;
                    }

                    float damping = 0.5f;//阻尼值
                    float height = getHeight();
                    if (height != 0) {
                        if (distance > height) {
                            damping = 0;
                        } else {
                            damping = (height - distance) / height;
                        }
                    }
                    if (currentY - startY < 0) {
                        damping = 1 - damping;
                    }

                    //阻力值限制再0.3-0.5之間,平滑過度
                    damping *= 0.25;
                    damping += 0.25;

                    moveHeight = moveHeight + (deltaY * damping);

                    childView.layout(topRect.left, (int) (topRect.top + moveHeight), topRect.right,
                            (int) (topRect.bottom + moveHeight));
                }
                break;
            case MotionEvent.ACTION_UP:
                if (!topRect.isEmpty()) {
                    //開始回移動畫
                    upDownMoveAnimation();
                    // 子控件回到初始位置
                    childView.layout(topRect.left, topRect.top, topRect.right,
                            topRect.bottom);
                }
                //重置一些參數(shù)
                startY = 0;
                currentY = 0;
                topRect.setEmpty();
                break;
        }

        return super.dispatchTouchEvent(event);
    }

    // 初始化上下回彈的動畫效果
    private void upDownMoveAnimation() {
        TranslateAnimation animation = new TranslateAnimation(0.0f, 0.0f,
                childView.getTop(), topRect.top);
        animation.setDuration(600);
        animation.setFillAfter(true);
        //設(shè)置阻尼動畫效果
        animation.setInterpolator(new DampInterpolator());
        childView.setAnimation(animation);
    }

    public class DampInterpolator implements Interpolator {
        @Override
        public float getInterpolation(float input) {
            //沒看過源碼,猜測是input是時間(0-1),返回值應(yīng)該是進(jìn)度(0-1)
            //先快后慢,為了更快更慢的效果,多乘了幾次,現(xiàn)在這個效果比較滿意
            return 1 - (1 - input) * (1 - input) * (1 - input) * (1 - input) * (1 - input);
        }
    }
}

參考鏈接:

https://my.oschina.net/u/1462828/blog/1553433
https://blog.csdn.net/u012230055/article/details/80000887

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容