Android: Automatically change layout for portrait and landscape orientations

One of the nicer things about using layouts for your design is the ability to automatically move things around when the screen rotates.

Normally, layout files go in res/layout/. You can create an extra folder res/layout-land/ (for landscape mode) and res/layout-port/ (for portrait mode) and it should pick the appropriate layout.

When I first gave this a go, I thought something was wrong. Even on portrait orientation, it kept picking the file from /res/layout-land rather than /res/layout/!

I read both Supporting Multiple Screens: Designing alternative layouts and drawables and Providing Resources: How Android Finds the Best-matching Resource but none of them seemed to mention this.

But alas, a little trial and error proved successful. If you've got an alternate layout in /res/layout-land/, you must place the normal portrait layout in /res/layout-port/ rather than /res/layout/.

So before the changes, my incorrect resource structure looked like this:

  • res/
    • layout/
      • auto_rotate.xml
      • normal_layout.xml
    • layout-land/
      • auto_rotate.xml

What it's supposed to look like is:

  • res/
    • layout/
      • normal_layout.xml
    • layout-land/
      • auto_rotate.xml
    • layout-port/
      • auto_rotate.xml


Now stop playing around and get some damn work done!

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog