1

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 in 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.

inazaruk
  • 74,247
  • 24
  • 188
  • 156
Khushboo
  • 3,095
  • 2
  • 23
  • 24

1 Answers1

1

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).

inazaruk
  • 74,247
  • 24
  • 188
  • 156
  • 1
    Numerous?? Well, in that case, a list view would be more efficient. – Kumar Bibek Jul 11 '11 at 09:49
  • I'm not sure I understood your comment. Could you please elaborate? – inazaruk Jul 11 '11 at 09:49
  • This can be done with a list view as well. 1. TextView 2. ListView – Kumar Bibek Jul 11 '11 at 09:51
  • Well, yes, he can add items to `ListView` instead of `LinearLayout`. But that was not the question. He asked what is better - inflate layout from xml or create `RelativeLayout` in code. – inazaruk Jul 11 '11 at 09:53
  • Hmmm. Well in that case, View creation itself takes a lot of time and resources. If you add to that inflating a layout everytime, I think 2nd option would be better. But, anyway, I would still suggest him to use a ListView here. – Kumar Bibek Jul 11 '11 at 09:59
  • What do you mean by "every time"? From what I understood he wants to create layout once in his `onCreate`. Also I'd say there is not enough context information to judge weather `ListView` is better or not. – inazaruk Jul 11 '11 at 10:06
  • Well, as mentioned, "Many" relative layouts, and "numerous". I assumed that he doesn't mean 5 or 6 or 7. – Kumar Bibek Jul 11 '11 at 11:33