/**
* @author JayChan
* @desc AppBarLayout快速滑動(dòng)導(dǎo)致回彈的解決方案,在AppBarLayout的布局里使用這個(gè)Behavior即可
* @date 2018/12/25 10:30
*/
public class AppBarLayoutBehavior extends AppBarLayout.Behavior {
private static final int TYPE_FLING = 1;
private boolean isFlinging;
private boolean shouldBlockNestedScroll;
public AppBarLayoutBehavior() {
}
public AppBarLayoutBehavior(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onInterceptTouchEvent(CoordinatorLayout parent, AppBarLayout child, MotionEvent ev) {
KLog.i("AppBarLayoutBehavior", "onInterceptTouchEvent:" + child.getTotalScrollRange());
shouldBlockNestedScroll = false;
if (isFlinging) {
shouldBlockNestedScroll = true;
}
return super.onInterceptTouchEvent(parent, child, ev);
}
@Override
public void onNestedPreScroll(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, int dx, int dy, int[] consumed, int type) {
//注意看ViewCompat.TYPE_TOUCH
KLog.i("AppBarLayoutBehavior", "onNestedPreScroll:" + child.getTotalScrollRange() + " ,dx:" + dx + " ,dy:" + dy + " ,type:" + type);
//返回1時(shí),表示當(dāng)前target處于非touch的滑動(dòng),
//該bug的引起是因?yàn)閍ppbar在滑動(dòng)時(shí),CoordinatorLayout內(nèi)的實(shí)現(xiàn)NestedScrollingChild2接口的滑動(dòng)子類還未結(jié)束其自身的fling
//所以這里監(jiān)聽子類的非touch時(shí)的滑動(dòng),然后block掉滑動(dòng)事件傳遞給AppBarLayout
if (type == TYPE_FLING) {
isFlinging = true;
}
if (!shouldBlockNestedScroll) {
super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed, type);
}
}
@Override
public void onNestedScroll(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, int dxConsumed, int dyConsumed, int
dxUnconsumed, int dyUnconsumed, int type) {
KLog.i("AppBarLayoutBehavior", "onNestedScroll: target:" + target.getClass() + " ," + child.getTotalScrollRange() + " ,dxConsumed:"
+ dxConsumed + " ,dyConsumed:" + dyConsumed + " " + ",type:" + type);
if (!shouldBlockNestedScroll) {
super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, type);
}
}
@Override
public void onStopNestedScroll(CoordinatorLayout coordinatorLayout, AppBarLayout abl, View target, int type) {
super.onStopNestedScroll(coordinatorLayout, abl, target, type);
isFlinging = false;
shouldBlockNestedScroll = false;
}
}
在布局文件中引用

clipboard.png