Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Android Devs: You're Doing LayoutInflater Wrong

DZone's Guide to

Android Devs: You're Doing LayoutInflater Wrong

· Java Zone
Free Resource

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

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.


Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat

Topics:

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}