In this tutorial we’ll override the ListView class to suit it according to our requirements in the android application.

Android Non Scrollable ListView Requirement

A ListView comes up with its own default scrolling methods. Now if we wish to create a layout which contains a ListView along with some other views inside a parent ScrollView then you’ll notice that the scrolling gestures of the ListView don’t work as desired.

The reason for this is that scrolling gestures received by the layout, they are all handled by the parent layout only. One workaround is to add the other views as the headers and footers of the ListView and avoid using ListView and ScrollView. But a more robust option is to create custom ListView class to suit it to our needs by making it non scrollable.

In this tutorial we’ll develop a custom ListView class and use it in a ScrollView with other child views. We’ll use Butterknife to bind the views.

Project Structure

The project consists of a MainActivity and a subclass of ListView named NonScrollListView.

android-nonscroll-listview-project

Code

The NonScrollListView class is given below:

onMeasure() allows us to specify how big you want your custom view to be with respect to the layout constraints of the parent class. AT_MOST typically means the layout_width or layout_height value was set to match_parent or wrap_content where a maximum size is needed (this is layout dependent in the framework), and the size of the parent dimension is the value.

The layout of the MainActivity is given below:
activity_main.xml

The package name of the custom ListView class is set as the tag. The layout consists of four buttons inside a RelativeLayout that’s the child of the a ScrollView.

The MainActivity.java is given below:

We’ve used a new default list layout android.R.layout.simple_expandable_list_item_2. It consists of two textViews that can be only invoked using ids : android.R.id.text1 and android.R.id.text2. The ListView is populated using a LinkedList of String arrays.

The output of the application in action is given below:

android-nonscroll-listview-output

Note: Replace the NonScrollListView with a normal ListView in the xml and the code. The following output is returned.

android-nonscroll-listview-output-2

As you can see the ListView default scrolls conflict with the ScrollView’s hence the gestures are not handled properly.

Alternate Way

A workaround to the above problem without creating a custom widget is given below:

This brings an end to this tutorial. You can download the final Android Custom Non Scrollable ListView Project from the link below.

By admin

Leave a Reply