Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I inflate a layout or programmatically create it?

Regarding Android programming,

This question has been bothering me for a while, should I inflate layout as much as possible or should I programmatically create the layouts as much as possible?

If we put "convenience" aside which is better? faster? safer? Any concrete inputs are greatly appreciated.

Regards,

like image 328
LuckyMe Avatar asked Apr 25 '13 07:04

LuckyMe


People also ask

What does it mean to inflate a layout Android?

"Inflating" a view means taking the layout XML and parsing it to create the view and viewgroup objects from the elements and their attributes specified within, and then adding the hierarchy of those views and viewgroups to the parent ViewGroup.

What does layout inflator do?

The LayoutInflater class is used to instantiate the contents of layout XML files into their corresponding View objects. In other words, it takes an XML file as input and builds the View objects from it.

What is layout inflation?

android.view.LayoutInflater. Instantiates a layout XML file into its corresponding View objects. It is never used directly. Instead, use Activity.

What does Inflater inflate do?

inflater.inflate will -Inflate a new view hierarchy from the specified xml resource. Throws InflateException if there is an error. In simple terms inflater. inflate is required to create view from XML .


1 Answers

I see, so inflating is the Google/Android recommended and conventional way of doing layouts

Yes.

and it doesn't slow down the runtime of the application by much

It doesn't slow down the runtime of the application by much when compared to doing the same work yourself in Java.

Because I read somewhere on the developer site of Android that it is a slow process and views should be "reused" as much as possible before resorting to inflating.

Recycling views in an AdapterView -- the most likely place for you to have read that advice -- is important, because recycling views is faster than creating views, no matter how those views are created. Again, the comparison is not between inflation versus rolling your own Java code, but between inflation and not creating new views.

should I inflate layout as much as possible or should I programmatically create the layouts as much as possible?

Inflate, please.

which is better?

Inflation takes into account resource sets (e.g., different layouts based on screen size and orientation). Inflation takes into account overrides of styles. Inflation works better with tooling.

faster?

There are probably some scenarios where hard-coded Java is faster than inflation, just as there are some scenarios in which hard-coded assembly language is faster than C. In most cases, the speed difference is not important enough to warrant the hassle.

safer?

I do not know what you consider "safe" to mean in this context.

like image 52
CommonsWare Avatar answered Sep 19 '22 15:09

CommonsWare