Search code examples
androidlistviewandroid-fragmentsandroid-scrollview

Make activity with fragments scroll as if one long page


I have an activity that consists of a few fragments (all containing listviews) in a vertical linear layout. Right now, each list itself is scrollable, but what I want is for the entire activity to scroll as if everything were just one long page.

I've tried adding a scrollview around the container that I'm adding the fragments to, checking every single property that seems to be relevant, but to no avail. How can I make this work?

enter image description here

XML of the activity's layout

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout (...)
    app:layout_behavior="@string/appbar_scrolling_view_behavior" >

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center_horizontal"
        android:layout_alignParentEnd="true"
        android:layout_alignParentStart="true"
        android:fillViewport="true"
        android:touchscreenBlocksFocus="true"
        android:importantForAccessibility="yes">

        <LinearLayout
            android:id="@+id/fragment_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">
        </LinearLayout>

    </ScrollView>

</RelativeLayout>

Solution

  • public class ListViewForScrollView extends ListView {
        public ListViewForScrollView(Context context) {
            super(context);
        }
    
        public ListViewForScrollView(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        public ListViewForScrollView(Context context, AttributeSet attrs,
        int defStyle) {
            super(context, attrs, defStyle);
        }
    
        @Override
        /**
         * rewrite this method to let listview be suitable for scrollview.
         * after that, you can use ListViewForScrollView in ScrollView
         */
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
        MeasureSpec.AT_MOST);
            super.onMeasure(widthMeasureSpec, expandSpec);
        }
    }