解决NestedScrollView中ViewPager不显示的问题

Posted by Mio4kon on 2016-01-12

http://stackoverflow.com/a/33385207/4035627

最近碰到一个问题,当NestedScrollView里面有ViewPager时,
ViewPager不显示.
代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<android.support.v4.widget.NestedScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="@+id/nest_scrollview"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="mio.kon.yyb.nestedscrollviewbug.ScrollingActivity"
tools:showIn="@layout/activity_scrolling">
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

这个时候会发现ViewPager就不会正常显示.

翻了下NestedScrollView的源码,发现在onMeasure的时候,有个mFillViewport参数很可疑.
怀疑是mFillViewport导致了子View不能进行测量.看了下注释发可能性很大,于是尝试改了改了一下:

1
2
NestedScrollView scrollView = (NestedScrollView) findViewById (R.id.nest_scrollview);
scrollView.setFillViewport (true);

成功!ViewPager可以正常显示了!

如图:

Update:

Note that this can be set in XML as well, just add android:fillViewpor‌​t=”true” to the NestedScrollView object. The documentation describes this attribute as Defines whether the scrollview should stretch its content to fill the viewport.