Two last concepts to go over before we dive into the intricacies of Project 2. It’ll be good to have a slight background of Custom List Adapters and Recycling ListViews before we go in.
Custom List Adapters
If you’ve been faithfully following the How-To Guide so far, Custom List Adapters are not a far-fetched idea. Previously, we used Android’s handy
simple_item_1 layout in conjunction with the ArrayAdapter. In this project, we want to display a track name, number of plays and the note count of a track. Unfortunately,
simple_item_1 and even the
simple_item_2 layouts won’t help us here. We need to make our own layout custom tailored to our needs.
This means that not only will we have to build a custom layout for our needs but also a custom adapter that can work with it. Ugh, I know, more work. I was pretty put off by custom list adapters in the beginning as well because of this, but it’s all necessary and gets easier with practice! Just to re-iterate, the steps we will take to create a custom list adapter:
- Make an xml layout for what an item in our ListView will look like
- Create an custom adapter that will correctly configure the ListView item
Lastly, there’s this concept of recycling ListViews. What does that even mean? Since we used the ArrayAdapter in the last project, we were abstracted a bit from the inner workings of ListViews. Had we not chosen an ArrayAdapter and instead used a BaseAdapter customized to our liking, within that adapter we would have written code that does the following:
- Passed our data array into the adapter
- Create a ListView Item for each item in the data array.
- Project Item onto ListView using the
The methodology above would equate to 1,000 listView items being created if there were 1000 entries in our data array. But if you think about it, at any time on the app, the user only sees a subset of this data array, so do we really need to load 1,000 listView items if only 10 can fit on a screen at one time?
That’s where the idea of recycling ListViews comes in! Instead of loading all the items in our data array and creating an item for each one, let’s recycle our ListView items views!
Take a look at the lovely graphic from android.amberfog. Say the visible screen of the user can only see 7 listView items at once. When the user scrolls up to reveal more listView items, we take the ListView item that has disappeared off screen and use it’s shell to populate the data with new data. We will be accomplishing this with the
convertView() method later on.
By recycling listView items, we are only creating 7 (or how ever many fit on the screen at one time) ListView items instead of creating one for the entire array. We consume and save a lot more memory this way! This is an optimization technique to improve the memory usage and performance of your app.
Awesome. That was a lot to swallow but hopefully was enough for you to hold on to while we go into Project 2! You got this homie.