Asynchronous layout inflation

With recent release of Android Support Library, revision 24 Google developers baked into v4 library a new helper class for asynchronous inflation of layouts.

Enter AsyncLayoutInflater

You will find use for AsyncLayoutInflater in cases when you want to inflate parts of your applications UI lazily or as an response to users interactions. This helper class will allow your UI thread to continue being responsive while heavy inflation is being performed.

To use AsyncLayoutInflater you just have to create instance of it on your applications UI thread.

Consider this part of your Activity code (I’ll be using Kotlin syntax here):

And now with this instance you can inflate your layout file

As you can see the inflate function takes 3 parameter. First is your layout resource, second is optional view intended to be a parent of inflated hierarchy and third is a OnInflateFinishedListener, wich is a callback, that will be invoked once your layout has been inflated (in sample replaced by lambda function).

In comparsion the basic inflate function of LayoutInflater, that you would normaly use, takes boolean as a third parameter, that says whether the inflated hierarchy should be attached to the root parameter. As in our async version of inflate function there isn’t such a parameter you will most likely want to call in this way:

Drawbacks of using AsyncLayoutInflater

There are of course some drawbacks here:

  • 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

If layout that we are trying to inflate in asynchronous way can not be constructed in this way, the inflation process will automaticaly fall back to inflation on UI thread.

Small sample in Kotlin with use of Kotlin Android Extensions




Source: mostly source code for AsyncLayoutInflater class

I like to code. Opinions expressed here are my own

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store