出現(xiàn)的問(wèn)題:ViewPager中包含兩個(gè)Fragment惩系,這兩個(gè)Fragment的內(nèi)容是一樣的位岔。如果Fragment中沒(méi)有內(nèi)容的話(huà),滑上去下面會(huì)有一大片空白堡牡。如下圖1表示未滑動(dòng)時(shí)的效果圖抒抬,圖2表示滑動(dòng)以后的效果圖,圖2中下面一片空白晤柄,不擦剑。
現(xiàn)在需求是滑動(dòng)時(shí),下面沒(méi)有數(shù)據(jù)可免,就不再滑動(dòng)從而導(dǎo)致顯示整屏空白抓于。
分析:下面沒(méi)數(shù)據(jù)時(shí)做粤,滑動(dòng)AppBarLayout浇借,不需要滑動(dòng)完整個(gè)AppBarLayout。那么這個(gè)AppBarLayout滑動(dòng)多少距離合適呢怕品,可滑動(dòng)距離就是AppBarLayout的高度 + 懸浮布局高度 + recyclerView的高度 - CoordinatorLayout布局的高度妇垢,這樣保證剩下的正好是個(gè)全屏。先看下修改前和修改后的效果圖肉康。
以下是代碼闯估,帶部分注釋?zhuān)胁欢目梢詥?wèn)
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) {
// 重寫(xiě)此方法,判斷offset是否超過(guò)了最大的可滑動(dòng)距離吼和,如果超過(guò)就不再滑動(dòng)
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);
}
// 計(jì)算最大的可滑動(dòng)距離
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可滑動(dòng)的最大值涨薪,得到的值: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();
}
// 最大可滑動(dòng)距離就是AppBarLayout的高度 + 懸浮布局高度 + recyclerView的高度 - parentH
maxScrollH = childScrollTotalH - parentH + recyclerViewH + radioGroup.getMeasuredHeight();
if(maxScrollH < 0){
maxScrollH = 0;
}
}
}