Mister004
Mister004

Reputation: 303

Android GUI XML vs Code

I have a short question according to creating GUIs in android. What way is better xml or coding? I always read that xml is way better but imagine you have a scrollview. Inside the scrollview is a relativelayout. Inside that there shall be several rows with an ImageView next to a TextView next to a RadioButton. The number of rows can vary. Is it really better to make lets say 50 Views in the xml or a loop in code where these views are created?

Upvotes: 2

Views: 3849

Answers (5)

m0skit0
m0skit0

Reputation: 25874

Each has its pros and cons. Just to name a few:

XML

  • pros -> fast GUI development, keep code clean
  • cons -> static

Dynamic (code)

  • pros -> able to react to runtime conditions
  • cons -> more code, which means poorer maintainability and potentially buggier

Upvotes: 7

ZOXIS
ZOXIS

Reputation: 608

I agree with the above. XML is a better approach to this even when you require dynamic updates you can still use XML bits and pieces to render the content. your code will be based on XML elements but XML files will be independent. hence if you break a funcitonality in the code you know that its your business logic thats broken not the UI part, which will make it easier to develop and find problems easily.

Upvotes: 1

keyser
keyser

Reputation: 19189

Dynamic content is, of course, added dynamically. So your example would require some java code. You should only add the dynamic part programmatically though, so you'd still use an xml document for the static parts (it's very unusual for a layout to be completely dynamic).

If you have a fixed number of views then yes, I'd write 50 of them in xml rather than with a loop. I guess you're wondering about code duplication and, as far as I know, you'll get some when using xml.

(One way to minimize code duplication within xmls' is with the usage of styles and themes)

Upvotes: 1

Olivier.G
Olivier.G

Reputation: 143

Why you do not use a ListView instead of a ScrollView. It will be simplier to implement and performances must be better with it.

Create a XML file with a ListView and in your activity implements your own adapter to instanciate the rows. You can find a lot of tutorials on internet talking about that, I'm sure you will find what you need ! Good luck.

Upvotes: 0

kosa
kosa

Reputation: 66677

If you need to add components dynamically, only way is go with code (or) mixed approach (define layout in XML and add components in code). If your components are static XML may be best.

Upvotes: 1

Related Questions