NestedScrollView could not scroll with match_parent height child

Norutan picture Norutan · May 13, 2016 · Viewed 47.9k times · Source

I implement NonSwipeableViewPager with a fragment has NestedScrollView like this, what I expect is that the scrollview can scroll up and show 2 textviews:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <include
                android:id="@+id/header"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                layout="@layout/header" />

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_centerHorizontal="true"
                android:layout_marginBottom="16dp"
                android:src="@drawable/ic_up" />

        </RelativeLayout>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Text 1" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Text 2" />

    </LinearLayout>

</android.support.v4.widget.NestedScrollView>

But it could not scroll, I tried many ways but still did not get any solution

Answer

Tim picture Tim · May 13, 2016
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

This linearlayout should have android:layout_height="wrap_content".

Reason for that is that if the scrollview's child is the same size as the scrollview itself (both match_parent for height) it means that there is nothing to scroll through, since they are of same size and the scrollview will only be as high as the screen.

If the linearlayout has a height of wrap_content then the height is not related to the height of the screen and the scrollview will be able to scroll through it.

Just remember that a scrollview can only have 1 direct child, and that child needs android:layout_height="wrap_content"