Category Archives: Android

Preload Admob ads in RecyclerView

The problem

You have a RecyclerView that displays content. Some of the content are ads (e.g. native Admob ads).

Normally, you would call NativeExpressAdView.loadAd() in the adapter’s onBindViewHolder().

Until the ad fully loads, the user will see blank space.
The goal is to avoid this issue. We’d like to have the ad ready when we need to bind.

Caching ads

We will create a helper class AdViewPool to cache the ads. Its implementation will follow later.

Note that the implementation will differ for yours, depending on the name of your ViewHolder and the items in the adapter, so please adjust it as needed.

In my case, I have a Fragment with a RecyclerView inside.
Inside the Fragment, I define an AdViewPool and initialize it in onCreateView() .

(It needs to be in onCreateView(), not onCreate(), so that layout parameters will work).

Retrieving ads from the pool

In onCreateViewHolder():

So instead of creating the view here, like we do for other view types, we retrieve it from the pool.

Putting back to the pool

When the view goes out of the screen, it must be put to the pool. For this, we override onViewDetachedFromWindow().

That’s it! No need to handle Model.TYPE_CONTENT_AD in onBindViewHolder (except if you want to do other things with it).

Implementation of AdViewPool

Here’s the implementation of AdViewPool. Adjust it as needed.

Pass the RecyclerView for root (3rd constructor parameter).