Customizing Layout for Various Screen Configurations

By now you know very well that Android offers a host of layout managers that help you build user interfaces. If you've played around with the layout managers that we've discussed, then you know that you can combine the layout managers in various ways to obtain the look and feel that you want. Even with all the layout managers, building Uls—and getting them right— can be a challenge. This is especially true for mobile devices. Users and manufacturers of mobile devices are getting more and more sophisticated, and that makes the developer's job even more challenging.

One of the challenges is building a UI for an application that displays in various screen configurations. For example, what would your UI look like if your application were displayed in portrait vs. landscape? If you haven't run into this yet, your mind is probably racing right now, wondering how to deal with this common scenario. Interestingly, and thankfully, Android provides some support for this use case.

Here's how it works: Android will find and load layouts from specific folders based on the configuration of the device. A device can be in one of three configurations: portrait, landscape, or square. To provide different layouts for the various configurations, you have to create specific folders for each configuration from which Android will load the appropriate layout. As you know, the default layout folder is located at res/layout. To support the portrait display, create a folder called res/layout-port. For landscape, create a folder called res/layout-land. And for square, create one called res/layout-square.

A good question at this point is, "With these three folders, do I need the default layout folder (res/layout)?" Generally, yes. Realize that Android's resource-resolution logic looks in the configuration-specific directory first. If Android doesn't find a resource there, it goes to the default layout directory. Therefore, you can place default-layout definitions in res/layout and the customized versions in the configuration-specific folders.

Note that the Android SDK does not offer any APIs for you to programmatically specify which configuration to load—the system simply selects the folder based on the configuration of the device. Also realize that the layout is not the only resource that is configuration-driven. The entire contents of the res folder can have variations for each configuration. For example, to have different drawables loaded per configuration, create folders for drawable-port, drawable-land, and drawable-square.

0 0

Post a comment