轉載請注明出處:
http://blog.csdn.net/aa464971/article/details/85246559
Github位址:https://github.com/xiandanin/AndroidViewHelper
效果圖

Gradle 引入
implementation 'com.dyhdyh:view-helper:1.0.3'
調用DesignViewHelper
//滾動AppBarLayout
DesignViewHelper.setAppBarLayoutOffset(appBar, offsetY);
//以動畫的形式滾動AppBarLayout
DesignViewHelper.setAppBarLayoutOffsetWithAnimate(appBar, offsetY, duration);
//滾動AppBarLayout到頂部
DesignViewHelper.scrollAppBarTop(appBar, isAnimate);
篇外話
得吐槽一下國内的技術文章環境是真的爛,這個問題查來查去不是你抄他就是他抄你,沒有一篇能夠有效的讓AppBarLayout滾動,那沒辦法隻能自己解決了。
翻了老半天的源碼,最終在
HeaderBehavior
中找到了
setHeaderTopBottomOffset
,過程很艱辛,結果很簡單,但是這個方法不是
public
的調不到,是以要用反射去調,已經封裝在
DesignViewHelper
,可以直接使用。
int setHeaderTopBottomOffset(CoordinatorLayout parent, V header, int newOffset) {
return this.setHeaderTopBottomOffset(parent, header, newOffset, -2147483648, 2147483647);
}
int setHeaderTopBottomOffset(CoordinatorLayout parent, V header, int newOffset, int minOffset, int maxOffset) {
int curOffset = this.getTopAndBottomOffset();
int consumed = 0;
if (minOffset != 0 && curOffset >= minOffset && curOffset <= maxOffset) {
newOffset = MathUtils.clamp(newOffset, minOffset, maxOffset);
if (curOffset != newOffset) {
this.setTopAndBottomOffset(newOffset);
consumed = curOffset - newOffset;
}
}
return consumed;
}