Best practices: Layouts on Android (Programmatic vs XML)

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.

Leave a Comment