Android 阻尼回弹效果简单实现(类似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初始时上下坐标位置(相对父View,
    // 即当前ReboundEffectsView)
    private boolean isEndwiseSlide;// 是否纵向滑动
    private float mVariableY;// 手指上下滑动Y坐标变化前的Y坐标值
    private float mVariableX;// 手指上下滑动X坐标变化前的X坐标值

    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);// 当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;// 消费touch事件
        }

        float nowX = e.getX();
        float diffX = (nowX - mVariableX) / 5;//除数越大可以滑动的距离越短
        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;// 消费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方向上当前触摸点的前一次记录位置
    private int previousY = 0;
    // y方向上的触摸点的起始记录位置
    private int startY = 0;
    // y方向上的触摸点当前记录位置
    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);
                }
                //重置一些参数
                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);
        //设置阻尼动画效果
        animation.setInterpolator(new DampInterpolator());
        childView.setAnimation(animation);
    }

    public class DampInterpolator implements Interpolator {
        @Override
        public float getInterpolation(float input) {
            //没看过源码,猜测是input是时间(0-1),返回值应该是进度(0-1)
            //先快后慢,为了更快更慢的效果,多乘了几次,现在这个效果比较满意
            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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,015评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,262评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,727评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,986评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,363评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,610评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,871评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,582评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,297评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,551评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,053评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,385评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,035评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,079评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,841评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,648评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,550评论 2 270

推荐阅读更多精彩内容