The last couple of years have seen the Android platform grow from strength to strength. Ever more powerful smart phones and an increasing number of tablets have been launched. As a result of this we have devices with typical screen sizes ranging from 4”, 7” to 10” inches. Not to mention varying screen densities. To top it all we then have the regular Android OS updates. No sooner is Android 4 (Jelly Bean) rolled out and we start to see the rumours for 5 (Key Lime Pie).
The question is how can a single App work to its best advantage on both a smart phone and tablet device? How do we make best use of that lovely extra screen space on the tablet device?
This is where fragments come in. The concept of fragments was introduced with Android 3 (Honeycomb) to solve the conundrum of how to tackle an App layout working on a smart phone or a tablet. A fragment can be thought of as a nugget of functionality.
Consider one of the most common interfaces that is seen on a smart phone. A list of items is presented; clicking on an item then displays a new page (‘Activity’). This is great on your 4” screen but not so clever on that 10” tablet that has just been purchased. A far better interface on the tablet would be the list of items occupying half of the screen and the remaining screen being used for the results.
This can be achieved by creating fragments for the list and detail functionality
· A fragment to manage the list is created.
· A fragment to manage the details is created.
These fragments are then referenced in the layouts that used to describe the screen. It is the management of these layouts where further Android ‘magic’ takes place. Our Android project will have a ‘res’ folder and it is here we can define further folders to cater for different screens (see below). The naming convention of the folder determines for what screen type the layouts contained within it would be used.
1. res/layout/main.xml (Used by the smart phone)
2. res/layout-sw720dp/main.xml (10” tablet)
When the App is now launched the appropriate layout will be used. This has allowed common code to be used across both devices with the functionality removed from the details of the layout (as all good software should be).
A final note you will have noticed that fragments were introduced with Android 4. Statistics from Google Play show that Gingerbread (3) is still the most common platform in use. This is dealt with by Google releasing a compatibility library to allow this and other rich functionality to be made available all the way back to Donut (1.6).