Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practices: Layouts on Android (Programmatic vs XML)

Tags:

android

This question has been bugging me for some time. I've already developed a couple of apps on the Android platform and somehow always find myself resorting to Java code in order to construct the layouts. In a professional development environment, is this acceptable? Or should XML files be the go-to approach? I usually find XML a more tedious approach and often, these layouts don't look the same on all devices. I just don't get it. From a professional viewpoint, has anyone really been able to develop apps with complex views purely using XML files? This question is killing me because Google recommends using XML but the UI never looks the same on all devices unless done programmatically. Or am I doing something wrong?

Note that I'm referring to Android 2.2 and 2.3, which majority of the users use.

like image 762
OckhamsRazor Avatar asked Mar 22 '12 17:03

OckhamsRazor


1 Answers

I use XML layouts on pretty much every fragment and activity of every app I write. I very rarely see any need to create Views dynamically, tho configuration of ListViews, showing/hiding views, etc needs doing in code. For me the advantages of XML are:

  • Ability to use layout editors (Eclipse)
  • Easier to preview layouts
  • Possible to benefit from auto-localisation of layouts
  • Easily maintain different parallel layouts for difference devices (screens)
  • Can get a sense of the layout by looking at it (easier than code)
  • Easy to break layouts down into pieces (fragments, includes, etc) to remove duplication
  • Keeps a separation between the visual design, and the functionality behind it

I can't think of any good reasons to put all my layouts into code - that sounds like hell.

I expect the reason your layouts don't look the same is because your XML is not defining the layouts correctly. Bear in mind the Android tools convert XML layouts into code, so there's no inherent problem with using XML layouts versus dynamic - both end up as code.

like image 195
Ollie C Avatar answered Sep 20 '22 03:09

Ollie C