解决CoordinatorLayout+AppBarLayout滑动抖动(回弹)问题

最近发现项目中一个使用CoordinatorLayout+AppBarLayout的界面发生了滑动不顺畅的问题,界面中使用了CoordinatorLayout,AppBarLayout,CollapsingToolbarLayout,Toolbar,RecyclerView,当向上滑动AppBarLayout并在惯性滑动未停止的时候滑动RecyclerView发生回弹

一、xml布局文件




    

        

            
            

            

                

                    

                    

                
            
        

        
    

    




app:layout_behavior="com.example.utils.FlingBehavior"这个是自定义的用来解决抖动问题

二、解决办法

自定义AppBarLayout.Behavior

public class FlingBehavior extends AppBarLayout.Behavior {
    private static final int TOP_CHILD_FLING_THRESHOLD = 3;
    private boolean isPositive;

    public FlingBehavior() {
        super();
    }

    public FlingBehavior(Context context, AttributeSet attrs) {
        super(context, attrs);
    }



    //fling上滑appbar然后迅速fling下滑recycler时, HeaderBehavior的mScroller并未停止, 会导致上下来回晃动
    @Override
    public void onNestedPreScroll(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, int dx, int dy, int[] consumed, int type) {
        if (type == ViewCompat.TYPE_NON_TOUCH && getTopAndBottomOffset() == 0) { //recyclerview的惯性比较大 ,会顶在头部一会儿, 到头直接干掉它的滑动
            ViewCompat.stopNestedScroll(target, type);
        }
        super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed, type);
    }

    @Override
    public boolean onInterceptTouchEvent(CoordinatorLayout parent, AppBarLayout child, MotionEvent ev) {
        if (ev.getAction() == ACTION_DOWN) {
            Object scroller = getSuperSuperField(this, "mScroller");
            if (scroller != null && scroller instanceof OverScroller) {
                OverScroller overScroller = (OverScroller) scroller;
                overScroller.abortAnimation();
            }
        }

        return super.onInterceptTouchEvent(parent, child, ev);
    }

    private Object getSuperSuperField(Object paramClass, String paramString) {
        Field field = null;
        Object object = null;
        try {
            field = paramClass.getClass().getSuperclass().getSuperclass().getDeclaredField(paramString);
            field.setAccessible(true);
            object = field.get(paramClass);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return object;
    }
    // --------------------------- end
}

你可能感兴趣的:(解决CoordinatorLayout+AppBarLayout滑动抖动(回弹)问题)