frankish frankish - 1 year ago 76
Android Question

What is the best way to make a scrolling gridview which virtualizes items in Android?

I want to use a gridview which can show 500 items easily. Like 3 items per line and many rows.. I don't want gridview to have REAL 500 items. For example if the screen can show 15 items at a time, I want it to reuse these items and replace their contents with the items corresponds to current scroll position. (Like the TableView in iOS or Virtualizing panels like in Windows 8 and Windows Phone 8).

Think about this like a photo application which lists the photos in 3 columns and you can scroll even 1000 items or 5000 items (it just take users own time to scroll to that deep, I just want the view to be able to handle items independent of their count)

How can I do this?

Answer Source

I have great news for you! The Adapter pattern was built for just this purpose.

Adapter - An Adapter object acts as a bridge between an AdapterView and the underlying data for that view. The Adapter provides access to the data items. The Adapter is also responsible for making a View for each item in the data set. See here for more.

GridView - GridView is a ViewGroup that displays items in a two-dimensional, scrollable grid. The grid items are automatically inserted to the layout using a ListAdapter. For an introduction to how you can dynamically insert views using an adapter, read Building Layouts with an Adapter.

Use the examples shown in these pages to learn how to use a GridView with an adapter, then modify the example code for the adapter to load your pictures from where ever you want instead of from R.drawables.

Pay special attention to the part in the ListAdapter getView() method, particularly the View convertView parameter that gets passed to getView(). That parameter will be a "Recycled" view if possible. (one that has fully exited the screen. and thus is longer being used) So by re-using it instead of creating new views every time you make it possible to scroll through a list of thousands of items while still only using exactly how many View objects it takes to show one full screens worth.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download