AsyncLayoutInflater: On the way to making the UI thread responsive

Kishan Maurya
ProAndroidDev
Published in
2 min readDec 31, 2019

--

Recently I was working on Google Maps with custom marker layout and I was inflating custom marker layout and creating bitmap from that layout as MarkerOptions accepts bitmap. So layout inflation + bitmap generation was happening in main-thread (fragment). This could create unresponsiveness and jank.

Layout Inflation

so, I search for this scenario and found AsyncLayoutInflater.

What is AsyncLayoutInflater?

Helper class for inflating layouts asynchronously.

When to use AsyncLayoutInflater?

This is intended for parts of the UI that are created lazily or in response to user interactions. This allows the UI thread to continue to be responsive & animate while the relatively heavy inflate is being performed.

How to use AsyncLayoutInflater?

Construct an instance of AsyncLayoutInflater on the UI thread and call inflate(int, ViewGroup, OnInflateFinishedListener). The AsyncLayoutInflater.OnInflateFinishedListener will be invoked on the UI thread when the inflate request has completed.

The inflate function takes 3 parameters. First is your layout resource, second is an optional view intended to be a parent of inflated hierarchy and third is an OnInflateFinishedListener, which is a callback.

AsyncLayoutInflater

It is equivalent to calling inflate(int, ViewGroup, boolean) with attachToRoot set to false.

If the layout that is trying to be inflated cannot be constructed asynchronously for whatever reason, AsyncLayoutInflater it will automatically fall back to inflating on the UI thread. So App crash will never occur due to this.

Things to remember while using AsyncLayoutInflater

  • parents function generateLayoutParams() has to be thread-safe
  • all views being constructed must not create any Handlers or call Looper.myLooper() function
  • no support for setting LayoutInflater.Factory nor LayoutInflater.Factory2
  • no support for inflating layouts containing fragments

References :
https://github.com/amalChandran/asyncLayoutInflator
https://www.youtube.com/watch?v=ZETNOieGZLA&feature=youtu.be
https://medium.com/@lupajz/asynchronous-layout-inflation-7cbca2653bf

Photo by Aaron Burden on Unsplash

Thanks for reading. Soon I will post more articles on android, core java.
till then happy learning… keep reading… :)

You could check out my other interesting topics here.

--

--