Dimension resources simplify the task of building and maintaining a flexible Android app that looks good on various devices. Follow these best practices when using dimension resources.
A benefit and frustration of developing for Android is the great variety of devices running the mobile OS. You can't plan for the exact configuration of every current and future Android device. Fortunately, the Android team created a flexible system to help developers make their apps look good on all devices.
Dimension resources are an important part of this system, yet they don't get as much attention as they should. Tutorial after tutorial on the web show hard-coded values in layout files. While that can make a tutorial concise, it strengthens bad coding habits that can be hard to break later.
Best practices of using dimension resources
Ideally, all Android apps should aim to support as many devices as possible. By using dimension resources, you can greatly simplify the task of building and maintaining such a flexible app.
With dimension values, a single layout can scale to a variety of sizes and densities. The other option is to create a new layout file for every configuration, which can become a maintenance nightmare very quickly due to the duplicated code. Instead, having a single layout file that loads the appropriate dimension information at runtime will make your life simpler.
The following layout code uses dimension resources to display correctly on a variety of devices:
/>To support this layout, a number of resource targets can be created (Figure A). Figure A
Click the image to enlarge.
This might look like a little busy, however, each of the "values" targets only contains a single dimensions file with a few values.
<?xml version="1.0" encoding="utf-8"?>
In this example, the size and spacing of the banner, as well as the size of the title text, can be changed for each of the densities (ldpi, mdpi, hdpi, and xhdpi) as well as the sizes (small, normal, large, xlarge). This isn't a comprehensive set of size and density targets, but it shows the structure; you can add additional targets as needed.
Through the emulator, remote test services, and your test devices, you can verify the results. If any special cases need to be handled, a new resource folder can be created with adjusted dimension values.
The next time you hard-code the same size values into your layouts over and over again, take the time to make them dimension resources. It will make your life much easier when you make adjustments to optimize for specific device types.Also read on TechRepublic: Delight Android users with your app's design