Tuesday, December 24, 2013

Handling ListView in Android

Android APIs provides many views i.e controls to present the information and interact with user. ListView is one among them. However for the sake of utilising the memory efficiently, Android system reuses the views in certain components.

ListView is a list of items to be displayed to the user from which he/she may choose an item. The item can either be a simple text or combination of image and text or still more complex layouts. When writing custom adapters to fit in data for such complex items in list, there would have been need to override the getView().

Issue
Now coming to the point, As said, android reuses the views. In case,there are more number of items in the list than that can be displayed to the user in the screen. In such cases, Listview is scrollable. Now when populating the data to such lists, you will get parameter in getView that identifies the position of the item that is inflated.

Say the screen can display 5 items. Populating data from either list or array using the position parameter will populate correctly for the first five items. From the next item onwards, getView() will be called only with the position parameter ranging from 0-4. Consequently, you will be able to see only the first five data in your data list getting repeated in the listview.


Solving the issue, 
Add these lines to the listview in xml,
       android:layout_height="0dp"
       android:layout_weight="1"

This solves the issue.

References :
http://lucasr.org/2012/04/05/performance-tips-for-androids-listview/
http://stackoverflow.com/questions/2618272/custom-listview-adapter-getview-method-being-called-multiple-times-and-in-no-co/2639159#2639159
http://stackoverflow.com/questions/10120119/how-does-the-getview-method-work-when-creating-your-own-custom-adapter

No comments:

Post a Comment