Android : Optimizing for Phones and Tablets with Fragments

Leave a Comment

The Benefits of Fragments

  • Can use a portion of the display or no display at all.
  • Allow logic to be encapsulated into smaller building blocks of the user interface, so it doesn’t need to be copied.
  • Can be reused and added dynamically to support larger screen sizes and different configurations.
While Fragments give a ton of flexibility to the user interface, they also require some code organization to be reusable and adaptable for diverse device configurations. In order for Fragments to perform well on phones, phablets, and tablets in all orientations, these guidelines should be followed:
  1. Break down the user interface into standalone Fragments, which perform a specific task.
    • A Fragment should be a piece of functionality that is modular, self-contained, with its own layout (if needed) and behavior.
  2. Create generic, flexible Fragments.
    • Ensure Fragments do not make assumptions about how they will be used, or what other components will be used with them, to prevent coupling of code.
    • Allow Fragments to be configurable, allowing the look and behavior to be set at runtime.
    • Make Fragment layouts stretchable, optimize in small or large amounts of space.
  3. Use resource identifiers to optimize for different displays.
    • Provide alternate resources (images, font sizes, layouts, etc.) for different screen sizes, orientations, and densities.
  4. Require the parent Activity (or parent Fragment) to manage all of its child Fragments’ communication.
    • Fragments should only be aware of their parent and communicate with it through interfaces.
    • Parent Activities (or parent Fragments) should handle communication from their children Fragments, and take necessary action based upon the current application state.
    • Fragments should not interact with sibling Fragments directly, since there is no guarantee of the existence or state of sibling Fragments.

The Final Product

  

Source Code

The full source of this example can be download from this link.

Summary

Fragments are powerful tools used for building dynamic, flexible, and optimized user interfaces for Android applications. However, an organized design and architecture is required to get the best use of Fragments.
  • Break application user interfaces down into basic standalone components, and use Fragments to implement those components.
  • Create flexible and adaptable Fragments, that don’t make assumptions.
  • Handle Fragment communication through Fragment parents or global event buses.
  • Use Fragments even when alternate layouts are not used by the application, which will make adding tablet support much easier later on.
Android has come a long way in a short period of time, and will continue to evolve with mobile devices. By following some simple guidelines, it is possible to optimize applications to take advantage of every Android device.

0 comments:

Post a Comment