Search code examples
androidandroid-layoutandroid-linearlayoutandroid-xmlandroid-relativelayout

Android - Scrolling without a ScrollBar


I have the following layout (for brevity sake, I removed the different attributes):

<RelativeLayout>
    <LinearLayout>
        <android.support.v7.widget.Toolbar/>
        <LinearLayout android:id="@+id/item1"/>
        <LinearLayout android:id="@+id/item2"/>
        <LinearLayout android:id="@+id/item3"/>
        <ListView/>
    </LinearLayout>
    <android.support.design.widget.FloatingActionButton/>
</RelativeLayout>

I am trying to get this whole page to be scrollable. At the moment, only the ListView scrolls. Any idea how to do? Note that I cannot use ScrollView due to the fact that I embed a ListView. Also, the outer element must be RelativeLayout as I need the FloatingActionButton to be fixed regardless of scrolling.


Solution

  • Having a ListView inside a ScrollView would cause you a lots of trouble. Instead leave only the ListView in your layout

    <RelativeLayout>
        <LinearLayout>
            <android.support.v7.widget.Toolbar/>
            <ListView/>
        </LinearLayout>
        <android.support.design.widget.FloatingActionButton/>
    </RelativeLayout>
    

    and move your LinearLayouts into separate file (for example header.xml)

    <LinearLayout>
        <LinearLayout android:id="@+id/item1"/>
        <LinearLayout android:id="@+id/item2"/>
        <LinearLayout android:id="@+id/item3"/>
    </LinearLayout>
    

    You can then add the layout as header to your ListView with

    ListView listView = (ListView) findViewById(R.id.list);
    View header = LayoutInflater.from(context).inflate(R.layout.header, listView, false);
    listView.addHeaderView(header); // call before you set adapter!
    

    Now the whole view will be scrollable. If you use onItemClickListener don't forget that the index is shifted by listView.getHeaderViewsCount().