开发者

Inflate an xml file or create new intance of View in loop?

I am creating a screen/xml which has:

  1. TextView (Header)

  2. LinearLayout (placeholder to contain numerous RelativeLayouts)

I need to add many RelativeLayout (containing two TextViews) to the LinearLayout (mentioned above) in loop. This basically would be list of RelativeLayouts. I have two ways doing this:

  1. Create an xml file which has the RelativeLayout (and two TextViews under it). Inflate this i开发者_运维百科n the code again and again( in loop).And then add this to LinearLayout mentioned above.
  2. Create the instance of RelativeLayout and TextView using the keyword "new". And add the instances to the above mentioned LinearLayout.

Which is the least expensive way.


You should go with #1 approach - inflate layout from xml file. That's because its better to keep your code separate from your UI. You can preview and redesign your xml much easier using ADT tools, you can reuse this xml later for similar purposes and so on.

While code that creates UI is hard to read and hard to maintain, and its hard to design a proper UI using code only.

In general, its better to keep as much UI related stuff in xmls/resources. And fall back to code when its easier to use code (like creating 10 buttons with same text) or the only way to go (like dynamically generating some views).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜