Should I inflate a layout or programmatically crea

2020-02-10 14:32发布

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,

1条回答
孤傲高冷的网名
2楼-- · 2020-02-10 15:29

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.

查看更多
登录 后发表回答