首页 > 其他分享 >仿淘宝京东拖拽商品详情页上下滚动黏滞效果

仿淘宝京东拖拽商品详情页上下滚动黏滞效果

时间:2023-05-01 16:10:49浏览次数:47  
标签:MotionEvent return int private 黏滞 详情页 ev 拖拽 view


比较常用的效果,有现成的,如此甚好!:)

import android.content.Context;
import android.content.res.TypedArray;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
import android.widget.LinearLayout;
import android.widget.Scroller;

import com.snail.labaffinity.R;
import com.snail.labaffinity.adapter.SlideFragmentPagerAdapter;

/**
 * 1 ViewPager+TabLayout as content
 * 2 FragmentTabHost+Fragment as content
 * 3 bug :can not assertain which View is inTouch
 */

public class DragScrollDetailsLayout extends LinearLayout {


    public interface OnSlideFinishListener {
        void onStatueChanged(CurrentTargetIndex status);
    }

    public enum CurrentTargetIndex {
        UPSTAIRS,
        DOWNSTAIRS;

        public static CurrentTargetIndex valueOf(int index) {
            return 1 == index ? DOWNSTAIRS : UPSTAIRS;
        }
    }

    private static final float DEFAULT_PERCENT = 0.3f;
    private static final int DEFAULT_DURATION = 400;


    private int mMaxFlingVelocity;
    private int mMiniFlingVelocity;
    private int mDefaultPanel = 0;
    private int mDuration = DEFAULT_DURATION;
    private float mTouchSlop;
    private float mDownMotionY;
    private float mDownMotionX;
    private float mInitialInterceptY;

    public void setPercent(float percent) {
        mPercent = percent;
    }

    private float mPercent = DEFAULT_PERCENT;
    /**
     * flag for listview or scrollview ,if child overscrolled ,do not judge view region 滚过头了,还是可以滚动
     */
    private boolean mChildHasScrolled;

    private View mUpstairsView;
    private View mDownstairsView;
    private View mCurrentTargetView;

    private Scroller mScroller;

    private VelocityTracker mVelocityTracker;
    private OnSlideFinishListener mOnSlideDetailsListener;
    private CurrentTargetIndex mCurrentViewIndex = CurrentTargetIndex.UPSTAIRS;

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

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

    public DragScrollDetailsLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.DragScrollDetailsLayout, defStyleAttr, 0);
        mPercent = a.getFloat(R.styleable.DragScrollDetailsLayout_percent, DEFAULT_PERCENT);
        mDuration = a.getInt(R.styleable.DragScrollDetailsLayout_duration, DEFAULT_DURATION);
        mDefaultPanel = a.getInt(R.styleable.DragScrollDetailsLayout_default_panel, 0);
        a.recycle();
        mScroller = new Scroller(getContext(),new DecelerateInterpolator());
        mTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
        mMaxFlingVelocity = ViewConfiguration.get(getContext()).getScaledMaximumFlingVelocity();
        mMiniFlingVelocity = ViewConfiguration.get(getContext()).getScaledMinimumFlingVelocity();
        setOrientation(VERTICAL);
    }

    public void setOnSlideDetailsListener(OnSlideFinishListener listener) {
        this.mOnSlideDetailsListener = listener;
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();

        final int childCount = getChildCount();
        if (1 >= childCount) {
            throw new RuntimeException("SlideDetailsLayout only accept childs more than 1!!");
        }
        mUpstairsView = getChildAt(0);
        mDownstairsView = getChildAt(1);
    }

    /**
     * requestDisallowInterceptTouchEvent guarantee DragScrollDetailsLayout intercept event as wish
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        requestDisallowInterceptTouchEvent(false);
        return super.dispatchTouchEvent(ev);
    }

    /**
     * intercept rules:
     * 1. The vertical displacement is larger than the horizontal displacement;
     * 2. Panel stauts is UPSTAIRS:  slide up
     * 3. Panel status is DOWNSTAIRS:slide down
     * 4. child can requestDisallowInterceptTouchEvent();
     */
    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        switch (ev.getActionMasked()) {
            case MotionEvent.ACTION_DOWN:
                mDownMotionX = ev.getX();
                mDownMotionY = ev.getY();
                if (mVelocityTracker == null) {
                    mVelocityTracker = VelocityTracker.obtain();
                }
                mVelocityTracker.clear();
                mChildHasScrolled=false;
                break;
            case MotionEvent.ACTION_MOVE:
                adjustValidDownPoint(ev);
                return checkCanInterceptTouchEvent(ev);
            default:
                break;
        }
        return false;
    }


    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        switch (ev.getActionMasked()) {
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                flingToFinishScroll();
                recycleVelocityTracker();
                break;
            case MotionEvent.ACTION_MOVE:
                scroll(ev);
                break;
            default:
                break;
        }
        return true;
    }


    private boolean checkCanInterceptTouchEvent(MotionEvent ev) {
        final float xDiff = ev.getX() - mDownMotionX;
        final float yDiff = ev.getY() - mDownMotionY;
        if (!canChildScrollVertically((int) yDiff,ev)) {
            mInitialInterceptY = (int) ev.getY();
            if (Math.abs(yDiff) > mTouchSlop && Math.abs(yDiff) >= Math.abs(xDiff)
                    && !(mCurrentViewIndex == CurrentTargetIndex.UPSTAIRS && yDiff > 0
                    || mCurrentViewIndex == CurrentTargetIndex.DOWNSTAIRS && yDiff < 0)) {
                return true;
            }
        }
        return false;
    }



    private void adjustValidDownPoint(MotionEvent event) {
        if (mCurrentViewIndex == CurrentTargetIndex.UPSTAIRS && event.getY() > mDownMotionY
                || mCurrentViewIndex == CurrentTargetIndex.DOWNSTAIRS && event.getY() < mDownMotionY) {
            mDownMotionX = event.getX();
            mDownMotionY = event.getY();
        }
    }

    private void scroll(MotionEvent event) {
        if (mCurrentViewIndex == CurrentTargetIndex.UPSTAIRS) {
            if (getScrollY() <= 0 && event.getY() > mInitialInterceptY) {
                mInitialInterceptY = (int) event.getY();
            }
            scrollTo(0, (int) (mInitialInterceptY - event.getY()));
        } else {
            if (getScrollY() >= mUpstairsView.getMeasuredHeight() && event.getY() < mInitialInterceptY) {
                mInitialInterceptY = (int) event.getY();
            }
            scrollTo(0, (int) (mInitialInterceptY - event.getY() + mUpstairsView.getMeasuredHeight()));
        }
        mVelocityTracker.addMovement(event);
    }

    private void recycleVelocityTracker() {
        if (mVelocityTracker != null) {
            mVelocityTracker.clear();
            mVelocityTracker.recycle();
            mVelocityTracker = null;
        }
    }

    /**
     * if speed is enough even though offset is not enough go
     */

    private void flingToFinishScroll() {

        final int pHeight = mUpstairsView.getMeasuredHeight();
        final int threshold = (int) (pHeight * mPercent);
        float scrollY = getScrollY();
        if (CurrentTargetIndex.UPSTAIRS == mCurrentViewIndex) {
            if (scrollY <= 0) {
                scrollY = 0;
            } else if (scrollY <= threshold) {
                if (needFlingToToggleView()) {
                    scrollY = pHeight - getScrollY();
                    mCurrentViewIndex = CurrentTargetIndex.DOWNSTAIRS;
                } else
                    scrollY = -getScrollY();
            } else {
                scrollY = pHeight - getScrollY();
                mCurrentViewIndex = CurrentTargetIndex.DOWNSTAIRS;
            }
        } else if (CurrentTargetIndex.DOWNSTAIRS == mCurrentViewIndex) {
            if (pHeight - scrollY <= threshold) {
                if (needFlingToToggleView()) {
                    scrollY = -getScrollY();
                    mCurrentViewIndex = CurrentTargetIndex.UPSTAIRS;
                } else
                    scrollY = pHeight - scrollY;
            } else if (scrollY < pHeight) {
                scrollY = -getScrollY();
                mCurrentViewIndex = CurrentTargetIndex.UPSTAIRS;
            }
        }
        mScroller.startScroll(0, getScrollY(), 0, (int) scrollY, mDuration);
        if (mOnSlideDetailsListener != null) {
            mOnSlideDetailsListener.onStatueChanged(mCurrentViewIndex);
        }
        postInvalidate();
    }


    private boolean needFlingToToggleView() {
        mVelocityTracker.computeCurrentVelocity(1000, mMaxFlingVelocity);
        if (mCurrentViewIndex == CurrentTargetIndex.UPSTAIRS) {
            if (-mVelocityTracker.getYVelocity() > mMiniFlingVelocity) {
                return true;
            }
        } else {
            if (mVelocityTracker.getYVelocity() > mMiniFlingVelocity) {
                return true;
            }
        }
        return false;
    }

    private View getCurrentTargetView() {
        return mCurrentViewIndex == CurrentTargetIndex.UPSTAIRS
                ? mUpstairsView : mDownstairsView;
    }

    @Override
    public void computeScroll() {
        super.computeScroll();
        if (mScroller.computeScrollOffset()) {
            scrollTo(0, mScroller.getCurrY());
            postInvalidate();
        }
    }

    /***
     * 复用已经实现的View,省却了测量布局之类的麻烦
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        measureChildren(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(getMeasuredWidth(), getMeasuredHeight());
    }

    protected boolean canChildScrollVertically(int offSet,MotionEvent ev) {
        mCurrentTargetView = getCurrentTargetView();
        return canScrollVertically(mCurrentTargetView, -offSet, ev);
    }

    /***
     * judge is event  is in current view
     * 判断MotionEvent是否处于View上面
     */
    protected boolean isTransformedTouchPointInView(MotionEvent ev, View view) {
        float x = ev.getRawX();
        float y = ev.getRawY();
        int[] rect = new int[2];
        view.getLocationInWindow(rect);
        float localX = x - rect[0];
        float localY = y - rect[1];
        return localX >= 0 && localX < (view.getRight() - view.getLeft())
                && localY >= 0 && localY < (view.getBottom() - view.getTop());
    }

    /***
     * first    can view self  ScrollVertically
     * seconde  if View is ViewPager only judge current page
     * third    if view is viewgroup check it`s children
     */
    private boolean canScrollVertically(View view, int offSet, MotionEvent ev) {

        if (!mChildHasScrolled && !isTransformedTouchPointInView(ev, view)) {
            return false;
        }
        if (ViewCompat.canScrollVertically(view, offSet)) {
            mChildHasScrolled = true;
            return true;
        }
        if (view instanceof ViewPager) {
            return canViewPagerScrollVertically((ViewPager) view, offSet, ev);
        }
        if (view instanceof ViewGroup) {
            ViewGroup vGroup = (ViewGroup) view;
            for (int i = 0; i < vGroup.getChildCount(); i++) {
                if (canScrollVertically(vGroup.getChildAt(i), offSet, ev)) {
                    mChildHasScrolled = true;
                    return true;
                }
            }
        }
        return false;
    }

    private boolean canViewPagerScrollVertically(ViewPager viewPager, int offset,MotionEvent ev) {
        View showView = ((SlideFragmentPagerAdapter) viewPager.getAdapter()).getPrimaryItem();
        return showView != null && canScrollVertically(showView, offset, ev);
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
    }


}




<declare-styleable name="DragScrollDetailsLayout">
        <!-- float value for indicate the moment of switch panel-->
        <attr name="percent" format="float"/>
        <!-- how long the animation keep-->
        <attr name="duration" format="integer"/>
        <!-- default panel to show after init-->
        <attr name="default_panel" format="enum">
            <enum name="front" value="0"/>
            <enum name="behind" value="1"/>
        </attr>
    </declare-styleable>




仿淘宝京东拖拽商品详情页上下滚动黏滞效果_android



http://www.open-open.com/lib/view/open1482476959653.html



自定义商品详情页


  • 仿淘宝京东拖拽商品详情页上下滚动黏滞效果_ide_02

  • 大小: 6 MB
  • main.zip (52.7 KB)
  • 下载次数: 3
  • 查看图片附件

标签:MotionEvent,return,int,private,黏滞,详情页,ev,拖拽,view
From: https://blog.51cto.com/u_5454003/6238913

相关文章

  • python+playwright 学习-57 svg 元素拖拽
    前言SVG英文全称为ScalablevectorGraphics,意思为可缩放的矢量图,这种元素比较特殊,需要通过name()函数来进行定位。本篇讲下关于svg元素的拖拽相关操作。拖拽svg元素如图所示,svg下的circle元素是可以拖动的比如往右拖动100个像素,那么cx的值由原来的cx="100"变成cx="200"通......
  • 在线设计Tkinter界面,生成Python代码,Tkinter布局助手,拖拽生成界面,tkinter designer,可视
    设计地址:https://www.pytk.net/tkinter-helper/? 运行演示  教程地址:https://www.pytk.net/tkinter.html 常用演示"""本代码由[Tkinter布局助手]生成当前版本:3.2.4官网:https://www.pytk.net/tkinter-helperQQ交流群:788392508"""fromtkinterimportmessag......
  • angularjs 拖拽实现方案
    最近有一个拖拽排序的功能遍历后无法直接读取index和item。换了一种思路实现功能<!DOCTYPEhtml><htmllang="en"ng-app="myApp"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width,......
  • python+playwright 学习-57 svg 元素拖拽
    前言SVG英文全称为ScalablevectorGraphics,意思为可缩放的矢量图,这种元素比较特殊,需要通过​name​()函数来进行定位。本篇讲下关于svg元素的拖拽相关操作。拖拽svg元素如图所示,svg下的circle元素是可以拖动的比如往右拖动100个像素,那么cx的值由原来的cx="100"变成......
  • 记录-因为写不出拖拽移动效果,我恶补了一下Dom中的各种距离
    这里给大家分享我在网上总结出来的一些知识,希望对大家有所帮助背景最近在项目中要实现一个拖拽头像的移动效果,一直对JSDom拖拽这一块不太熟悉,甚至在网上找一个示例,都看得云里雾里的,发现遇到最大的拦路虎就是JSDom各种各样的距离,让人头晕眼花,看到一个距离属性,大脑中的印象极......
  • vue3 拖拽操作学习
    AS-Editor组件git:https://gitee.com/was666/as-editor/tree/vue3.x/体验:http://was666.gitee.io/as-editor/#/home......
  • 【天猫】商品详情页数据采集+商品销量采集+商品视频采集+商品优惠券数据采集
    采集场景在淘宝首页(https://s.taobao.com/)输入关键词搜索,采集搜索后得到的商品列表页数据。示例中关键词为【连衣裙】,可根据需求进行更换,同时支持自动批量输入多个关键词。点击商品进入商品详情页面,拿到详情页面能够看到的数据。 采集字段采集字段包括关键字文本值,产品标题,店铺名......
  • 手动拖拽
    下载drag.jshttps://gist.github.com/sunzsh/ddb7c1d129c74222e9235bbdac407766      引入drag.jsmain.js引入importdragfrom'@tools/drag'挂载Vue.use(drag)调用定义需要移动的容器加v-dragv-drag的容器往外层找 找到第一个是position:a......
  • vue 拖拽功能实现
    前言最新项目里使用到了拖拽的功能,查阅资料后,看到一篇关于拖拽的详细文章:https://www.cnblogs.com/xiaohuochai/p/5886618.html基于此,记录下vue实现拖拽的过程,以下是编写的示例demo效果图:设置拖拽时,需要拖拽的元素要设置draggable=true及元素是否可拖动。默认是draggab......
  • element-plus实现列表拖拽切换位置、顺序(支持搜索)
    1.组件实现<template><el-popoverplacement="bottom"popper-class="interBarControl-setPopover":width="200":visible="visible"trigger="click"@click.stop="">......