NestedScrollView嵌套viewpager會出現兩個問題
1.viewpager無法顯示,高度爲0
2.嵌套後NestedScrollView無法滑動
先說第一個問題:
viewpager無法正常顯示,只需要在NestedScrollView內加入
android:fillViewport="true"
就可以了
<android.support.v4.widget.NestedScrollView
android:id="@+id/novice_live_scroll"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:overScrollMode="never"
android:fillViewport="true"
>
第二個問題,嵌套後NestedScrollView無法滑動,這個問題只要我們重寫一個viewpager,然後在xml裏用我們的viewpager就可以了
public class WrapContentHeightViewPager extends ViewPager {
public WrapContentHeightViewPager(Context context) {
super(context);
}
public WrapContentHeightViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int height = 0;
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
int h = child.getMeasuredHeight();
if (h > height) height = h;
}
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
如果viewpager內還嵌套了recycleview,只想讓nestedScrollView滑動,recyclerView只用來展示,那麼還需要對recyclerview進行處理,如下:
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false) {
@Override
public boolean canScrollVertically() {
return false;
}
};
recycler.setLayoutManager(linearLayoutManager);
記錄一個發現的小坑,有遇到這些問題的朋友,希望這個帖子可以幫到大家。