The Challenge: Memory

Suppose that our UI is supposed to look like this:

Settings App from Android 9.0
Settings App from Android 9.0

Here we have a vertically-scrolling list of items. Each item appears to have an ImageView and a pair of TextView widgets.

This happens to be from the Settings app on an Android 9.0 device. If you have spent much time with Settings, you know that while it has a bunch of top-level options like these, there are only so many. We could, if needed, have one ConstraintLayout in a ScrollView that managed them.

But what happens if our list needs to have thousands of items in it?

Each widget — TextView, Button, ImageView, etc. — takes up around 1KB of memory, not counting its content (text, image, whatever). Several thousand widgets means several MB of memory.

On Android, the amount of memory your app can use is limited. On very old or very cheap devices, it might be as little as 16MB, though higher values (e.g., 32MB, 48MB) are a bit more common today. Still, there is always a cap. Having one screen use several MB of memory will be a problem for apps that have lots of screens, particularly if many of those screens will have their own long lists.

AdapterView and RecyclerView are designed around recycling. If you look at that screenshot again, no matter how many rows there might be in the list overall, the user can only see 8 of them on this particular screen at once. View recycling takes advantage of this, so we can limit our memory usage. Rather than having widgets for each item in the list, we have widgets for each visible item, plus a few more to help with reacting to scrolling events. As rows in the list scroll off the screen, they become eligible for reuse (recycling). This helps keep our memory usage to a more reasonable level, despite having a potentially very long list.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.