ItemTouchHelper实现短按拖拽

实现方法:
将ItemTouchHelper中的GestureDetector的监听器给取出来,然后设置一个自定义的监听器进去,在自定义的监听器的短按事件onShowPress中去调用原监听器的长按方法onLongPress。我的实现代码如下,其中mDoDrag变量是为不让整个itemView都能拖拽 而加进去的,如果不需要可以删去:

public class ListenerInterceptor {
    private GestureDetector.OnGestureListener mListener2BeIntercept;
    private InterceptListener mListener2Intercept;

    private boolean mDoDrag = true;

    public ListenerInterceptor(ItemTouchHelper helper) {
        mListener2Intercept = new InterceptListener();

        try {
            Field fGesDetector = ItemTouchHelper.class.getDeclaredField("mGestureDetector");
            fGesDetector.setAccessible(true);
            Object objGesDetector = fGesDetector.get(helper);

            Field fImpl = GestureDetectorCompat.class.getDeclaredField("mImpl");
            fImpl.setAccessible(true);

            Object objImpl = fImpl.get(objGesDetector);


            Field fLis = null;
            try {
                fLis = objImpl.getClass().getDeclaredField("mListener");
            }catch (Exception e){e.printStackTrace();}

            Object oDet = null;
            if (fLis == null){
                Field fDet = objImpl.getClass().getDeclaredField("mDetector");
                fDet.setAccessible(true);

                oDet = fDet.get(objImpl);
                fLis = oDet.getClass().getDeclaredField("mListener");
            }
            fLis.setAccessible(true);

            mListener2BeIntercept = (GestureDetector.OnGestureListener) fLis.get(oDet);

            fLis.set(oDet, mListener2Intercept);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setDoDrag(boolean drag){
        mDoDrag = drag;
    }

    public class InterceptListener extends GestureDetector.SimpleOnGestureListener {
        @Override
        public void onShowPress(MotionEvent e) {
            if (mDoDrag)
                mListener2BeIntercept.onLongPress(e);
        }
    }
}

————————————————
版权声明:本文为CSDN博主「番茄大圣」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/tomatomas/article/details/54317919

你可能感兴趣的:(ItemTouchHelper实现短按拖拽)