Over a million developers have joined DZone.

Android Devs: You're Doing LayoutInflater Wrong

· Java Zone

What every Java engineer should know about microservices: Reactive Microservices Architecture.  Brought to you in partnership with Lightbend.

According to Dave Smith of Double Encore, if you're using LayoutInflater in your Android code and it looks something like this:

inflater.inflate(R.layout.my_layout, null);

You're doing it wrong.

The root of the problem, Smith argues, is in the parameters of the inflate() method. Some developers may not realize that there is more than one version of the inflate() method, each with different parameters, and may not understand the difference.

Key to the issue is understanding the purpose of the parent ViewGroup:

Have you noticed that every time the framework wants you to inflate a layout, they also pass you the parent ViewGroup it will eventually be attached to? Notice also that in most cases... it will throw an Exception later on if LayoutInflater is allowed to automatically attach the inflated view to the root.

So why do you suppose we are given this ViewGroup if we are not supposed to attach to it? It turns out the parent view is a very important part of the inflation process because it is necessary in order to evaluate the LayoutParams declared in the root element of the XML being inflated. Passing nothing here is akin to telling the framework “I don’t know what parent this view will be attached to, sorry.”

So, without that parent ViewGroup, the LayoutParams you specified in your layout XML are ignored, and defaults are generated. There aren't all that many options, so the defaults may be exactly what you wanted, but that's not ideal, and you won't even know anything's wrong.

There are exceptions, of course, which Smith explains - AlertDialog, for example, works a bit differently. Overall, though, it's an interesting problem, and a mistake that you could easily make for a long time without even realizing you're making a mistake.


Microservices for Java, explained. Revitalize your legacy systems (and your career) with Reactive Microservices Architecture, a free O'Reilly book. Brought to you in partnership with Lightbend.

Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}