出現(xiàn)的問題:ViewPager中包含兩個Fragment,這兩個Fragment的內(nèi)容是一樣的。如果Fragment中沒有內(nèi)容的話,滑上去下面會有一大片空白。如下圖1表示未滑動時的效果圖,圖2表示滑動以后的效果圖,圖2中下面一片空白,不。

EasyBook1.jpg

EasyBook2.png
現(xiàn)在需求是滑動時,下面沒有數(shù)據(jù),就不再滑動從而導(dǎo)致顯示整屏空白。
分析:下面沒數(shù)據(jù)時,滑動AppBarLayout,不需要滑動完整個AppBarLayout。那么這個AppBarLayout滑動多少距離合適呢,可滑動距離就是AppBarLayout的高度 + 懸浮布局高度 + recyclerView的高度 - CoordinatorLayout布局的高度,這樣保證剩下的正好是個全屏。先看下修改前和修改后的效果圖。

IMG_2nxz4n2.gif

IMG_hgynaq1.gif
以下是代碼,帶部分注釋,有不懂的可以問
public class AppBarBehavior extends AppBarLayout.Behavior {
private ViewPager viewPager;
private RadioGroup radioGroup;
private int maxScrollH = 0;
private int recyclerViewH = 0;
public AppBarBehavior() {
super();
}
public AppBarBehavior(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean setTopAndBottomOffset(int offset) {
// 重寫此方法,判斷offset是否超過了最大的可滑動距離,如果超過就不再滑動
if(maxScrollH <= Math.abs(offset)){
offset = - maxScrollH;
}
return super.setTopAndBottomOffset(offset);
}
@Override
public boolean onStartNestedScroll(CoordinatorLayout parent, AppBarLayout child, View directTargetChild, View target, int nestedScrollAxes, int type) {
return super.onStartNestedScroll(parent, child, directTargetChild, target, nestedScrollAxes, type);
}
@Override
public boolean onTouchEvent(CoordinatorLayout parent, AppBarLayout child, MotionEvent ev) {
return super.onTouchEvent(parent, child, ev);
}
@Override
public boolean onMeasureChild(CoordinatorLayout parent, AppBarLayout child, int parentWidthMeasureSpec, int widthUsed, int parentHeightMeasureSpec, int heightUsed) {
return super.onMeasureChild(parent, child, parentWidthMeasureSpec, widthUsed, parentHeightMeasureSpec, heightUsed);
}
@Override
public boolean onLayoutChild(CoordinatorLayout parent, AppBarLayout abl, int layoutDirection) {
calculateMaxScrollH(parent, abl);
return super.onLayoutChild(parent, abl, layoutDirection);
}
// 計算最大的可滑動距離
private void calculateMaxScrollH(CoordinatorLayout parent, AppBarLayout child){
viewPager = parent.findViewById(R.id.vp_content);
radioGroup = child.findViewById(R.id.rg_comment);
int parentH = parent.getMeasuredHeight();
/**
* 獲取AppBarLayout可滑動的最大值,得到的值:AppBarLayout的高度去掉懸浮的那塊高度
* 正好可以保證AppBarLayout完全隱藏掉并且懸浮布局顯示
*/
int childScrollTotalH = child.getTotalScrollRange();
MainFragmentPagerAdapter adapter = (MainFragmentPagerAdapter) viewPager.getAdapter();
CommentFragment fragment = (CommentFragment) adapter.getItem(0);
if(fragment.getRecyclerView() != null){
recyclerViewH = fragment.getRecyclerView().getMeasuredHeight();
}
// 最大可滑動距離就是AppBarLayout的高度 + 懸浮布局高度 + recyclerView的高度 - parentH
maxScrollH = childScrollTotalH - parentH + recyclerViewH + radioGroup.getMeasuredHeight();
if(maxScrollH < 0){
maxScrollH = 0;
}
}
}