RecyclerView Optimization (RecyclerView Optimization – Improved scroll performance)

Tram Ho

In this article, we will learn how to optimize RecyclerView performance in Android. With these optimizations we can make RecyclerView scroll smoother.

When we implement RecyclerView in our Android Apps, sometimes, we encounter problems like: RecyclerView scroll items are not smooth. It leads to a bad user experience as it seems our Android Apps are lagging.

Let’s see what we can do to improve the performance of RecyclerView and we get a smooth scrolling.

RecyclerView optimization techniques

Use Image Download Library

When the Garbage Collection (GC) runs on the main thread, one of the reasons the UI becomes unresponsive is constant memory allocation and allocation, which leads to running GC very often. By using the bitmap pool concept, we can avoid it.

The best part is that Image-Loading libraries like Glide, Fresco use this bitmap grouping concept. So always use the Image-Loading library.

Delegate all image-related tasks to these libraries.

Set the width and height of the image

If our image width and height are dynamic (not fixed) and we are fetching imageUrl from server.

If we don’t set the correct image width and height before, the UI will blink during the load transition and render the image into the ImageView.

So we should ask our BackEnd side to submit the image size or aspect ratio, accordingly, we can calculate the required ImageView width and height.

Then we’ll be able to only set the width and the height. Hence do not flicker. The problem has been resolved!

Do less in the onBindViewHolder method

Our onBindViewHolder method will do a lot less work. We should test our onBindViewHolder method and optimize it. We can see an improvement in our RecyclerView by doing so. Try not to put logic in the onBindViewHolder method.

Use the Notify Item RecyclerView API

Whenever we have a use case of deleting, updating, or adding items, use the Notify Item API.

Alternatively, you can use DiffUtil with the ListAdapter.

Avoid nested views

If possible, we should avoid nested views and try to make a flat (non-nested) view wherever possible. Nested performance reduces RecyclerView performance. Flat view improves performance.

Use setHasFixedSize

We should use this method if the heights of all items are equal.

Use setItemViewCacheSize

According to the official documentation: It sets the number of off-screen views to keep before adding them to the recycling view group. , allowing LayoutManager to reuse those views unmodified without going back to the Adapter to reattach them (calling onBindViewHolder).

Share the news now

Source : Viblo