How to scroll a ListView inside a ScrollView in Android?

by / Thursday, 19 September 2013 / Published in Android

ScrollView is a layout container for a view hierarchy that can be scrolled by the user, allowing it to be larger than the physical display. A ScrollView is a FrameLayout, meaning you should place one child in it containing the entire contents to scroll; this child may itself be a layout manager with a complex hierarchy of objects. A child that is often used is a LinearLayout in a vertical orientation, presenting a vertical array of top-level items that the user can scroll through.

You should never use a ScrollView with a ListView, because ListView takes care of its own vertical scrolling. Most importantly, doing this defeats all of the important optimizations in ListView for dealing with large lists, since it effectively forces the ListView to display its entire list of items to fill up the infinite container supplied by ScrollView.

In this example we will show how to scroll a ListView inside a ScrollView.

Code for layout:

Code for main.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="Fruits"
android:textSize="12pt"
android:padding="5dp"
android:textColor="#ffffff"
android:background="@drawable/background_inner"/>

<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
android:layout_marginTop="5dp"
android:gravity="center">

<ListView
android:id="@+id/list_fruit"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/background_inner"
android:cacheColorHint="#374c0e"
android:divider="@drawable/divider_gradient"
android:dividerHeight="5dp"
android:listSelector="@drawable/background_inner" >
</ListView>
</ScrollView>
</LinearLayout>

 

Code in MainActivity:

ListView listView;

listView.setOnTouchListener(new ListView.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_MOVE)
{
listView.scrollBy(0, 1);
}
return false;
}
});

 

 

TOP