遇到的问题描述:
嵌套后ViewPager中的view展示不出来,解决办法:重新设置Viewpager的高度
自定义viewpager
public class WrapViewPager extends ViewPager {
private int current;
private int height = 0;
/**
* 保存position与对于的View
*/
private HashMap<Integer, View> childrenViews = new LinkedHashMap();
private boolean isCanScroll = false;
public WrapViewPager(Context context) {
super(context, null);
}
public WrapViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setScanScroll(boolean isCanScroll) {
this.isCanScroll = isCanScroll;
}//切换tab的时候重新设置viewpager的高度
public void resetHeight(int current) {
this.current = current;
if (childrenViews.size() > current) {
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) getLayoutParams();
if (layoutParams == null) {
layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, height);
} else {
layoutParams.height = height;
}
setLayoutParams(layoutParams);
}
}
/**
* 保存position与对于的View
*/
public void setObjectForPosition(View view, int position) {
childrenViews.put(position, view);
}
@Override
public void scrollTo(int x, int y) {
super.scrollTo(x, y);
}
@Override
public boolean onTouchEvent(MotionEvent arg0) {
try {
if (isCanScroll) {
return super.onTouchEvent(arg0);
}
} catch (Exception e) {
}
return false;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent arg0) {
try {
if (isCanScroll) {
return super.onInterceptTouchEvent(arg0);
}
} catch (Exception e) {
}
return false;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (childrenViews.size() > current) {
View child = childrenViews.get(current);
child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
height = child.getMeasuredHeight();
}
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
调用的方法:创建三个自定义view,添加到view列表中
view1 = UserView(context)
viewpager.setObjectForPosition(goodView,0)
view2 = UserView(context)
viewpager.setObjectForPosition(middleView,1)
view3 = UserView(context)
viewpager.setObjectForPosition(badView,2)
pageList.add(view1) pageList.add(view2) pageList.add(view3)
监听viewpager
viewpager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
override fun onPageScrollStateChanged(p0: Int) {
}
override fun onPageScrolled(p0: Int, p1: Float, p2: Int) {
}
override fun onPageSelected(index: Int) {
viewpager.resetHeight(index)
//自己的代码实现
}
})
设置好后高度问题解决了,因自定义view为了防止tab切换时每次重新加载页面和数据,做了return处理,这里viewpager高度变化后,
NestedScrollView 的高度也许变化,监听是否到底部的事件得重新监听,放到return之前即可
scrollView.setOnScrollChangeListener(NestedScrollView.OnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->
if (scrollY == v.getChildAt(0).measuredHeight - v.measuredHeight) {
//到底了
if (isLoadMore) {
} else {
}
}
})
if (isLoading) { return}