Using ConstraintLayout for building complex UI elements in Android

Android Mar 7, 2022

ConstraintLayout is a new capability recently available in the Android ecosystem, that enables creation of complex UI elements with ease. In this blog, we will share our experiences of using ConstraintLayout for building complex user experiences for our Halodoc app.

What is ConstraintLayout?‌‌

A ConstraintLayout is a ViewGroup that allows you to position and size widgets in a flexible way. ConstraintLayout allows you to create large and complex layouts with a flat view hierarchy (no nested view groups).

ConstraintLayout vs other layouts:
ConstraintLayout can satisfy the requirement of both RelativeLayout and LinearLayout: Set relationships between sibling views and the parent layout (like RelativeLayout) and set weights for dynamic UI (which was only possible in LinearLayout). Even though it’s awesome, it fails to serve the purpose with simple UI layouts.

Something that you might know about ConstraintLayout

  • It is easier to use with Android Studio's Layout Editor. ConstraintLayout is mainly designed for the new programmers so that they can easily design the layout using the Visual Editor instead of building the layout by hand via XML
  • No nested view groups require for complex UI.
  • MotionLayout:
    It supports animations with MotionLayout. If you want to learn more about MotionLayout with demos (See MotionLayout examples). Carousel view can be set using MotionLayout. See here.
MotionLayout is a layout type that helps you manage motion and widget animation in your app. MotionLayout is a subclass of ConstraintLayout and builds upon its rich layout capabilities. You can also check MotionLayout's attributes here.
  • ConstraintSet:
    You can also set its constrain programmatically using ConstraintSet. To set constraints of ImageView to:

Use:

If you want to learn ConstraintLayout from scratch, please refer this official website. We will only learn about its properties and widgets, performance, and advantages in this blog.

ConstraintLayout Properties and Widgets:

  • Constraints:
    A constraint defines a relationship between two widgets in the layout and controls how those widgets will be positioned within the layout.

    The aim of the ConstraintLayout is to help reduce the number of nested views, which will improve the performance of our layout files.
  • Chains:
    Chains are a specific kind of constraint which allows us to share space between the views within the chain and control how the available space is divided between them with horizontal and vertical orientation. There are three possible modes for each orientation: spread, spread_inside, and packed.


Spread: the components of the respective chain will spread out this chain style is the default style.
Spread Inside: the widgets at the starting and end of the chain will align to the parent and the rest will occupy the space equally.
Packed: the chain components will be packed together. You can also adjust the bias of the packed chain using horizontal or vertical bias.

ConstrainLayout's chains.
  • Barrier:
    A Barrier references multiple widgets as input and creates a virtual guideline based on the most extreme widget on the specified side. For example, a left barrier will align to the left of all the referenced views.

Similarly, we can set barrier to end

  • Baseline:
    The baseline constraint allows use to align the baseline of multiple textviews, regardless of their text sizes.
    Baseline contains handles that can only be constrained to another baseline.
  • Dimensions:
    Sometimes we need to create views that have a fixed aspect ratio. This is particularly useful with ImageView we need to display images that come from a feed, and we know that any images we get will be a specific aspect ratio.

    For example, This allows us to position a view along the vertical axis using a bias value, this will be relative to its constrained position. app:layout_constraintVertical_bias="0.5".
  • Group:
    Groups is used when you want to handle visibility or motion with all its view.
    The Group in ConstraintLayout is just a loose association of views.
  • Guideline:
    A guideline is a visual guide that will not be seen at runtime that is used to align other views. Guidelines can be oriented either horizontally or vertically.

    To create a vertical guideline you do so by right-clicking on the blueprint view and selecting from Add Vertical Guideline the context menu. (Similar for Horizontal). Guideline can be set in percent, begin or end.

Performance:

To better understand the performance of ConstraintLayout, let's take a step back and see how Android draws views.

ConstraintLayout will give the best performance when complex UI like one screen has multiple nested layouts(non-constraint layout).

When a user brings an Android view into focus, the Android framework directs the view to draw itself. This drawing process comprises 3 phases(Measure, layout & draw):

  1. Measure: The system completes a top-down traversal of the view tree to determine how large each ViewGroup and View element should be. When a ViewGroup is measured, it also measures its children.
  2. Layout: Another top-down traversal occurs, with each ViewGroup determining the positions of its children using the sizes determined in the measure phase.
  3. Draw: The system performs yet another top-down traversal. For each object in the view tree, a Canvas object is created to send a list of drawing commands to the GPU. These commands include the ViewGroup and View objects' sizes and positions, which the system determined during the previous 2 phases.
Reference: googleblog.com

For more understanding of performance for constraintLayout, you can read android-developers.googleblog.com

Following are the advantages over other layouts

  1. You can convert your existing complex Layouts to simple flatten ConstraintLayout with just one right-click on your layout's Component Tree. (Refer)
  2. In addition to weights, we can apply horizontal and vertical bias which is nothing but the percentage of displacement from the centre. ( bias of 0.5 means centrally aligned. Any value less or more means corresponding movement in the respective direction ) .
  3. Another very important feature is that it respects and provides the functionality to handle the GONE views so that layouts do not break if some view is set to GONE through java code. More can be found here:
  4. Provides power of automatic constraint applying by the use of Blueprint and Visual Editor tool which makes it easy to design a page.‌‌‌‌‌‌‌‌‌‌

Conclusion:

We have learned that the ConstraintLayout comes in as a better and more efficient layout than other ones. We have also learned basic properties and widgets. In subsequent parts, we will delve into deeper ConstraintLayouts.

Reference:


Read More:

You can read more about other Android topics in our Halodoc blogs at https://blogs.halodoc.io/


Join us

Scalability, reliability and maintainability are the three pillars that govern what we build at Halodoc Tech. We are actively looking for engineers at all levels and if solving hard problems with challenging requirements is your forte, please reach out to us with your resumé at careers.india@halodoc.com.

About Halodoc

Halodoc is the number 1 all around Healthcare application in Indonesia. Our mission is to simplify and bring quality healthcare across Indonesia, from Sabang to Merauke. We connect 20,000+ doctors with patients in need through our Tele-consultation service. We partner with 3500+ pharmacies in 100+ cities to bring medicine to your doorstep. We've also partnered with Indonesia's largest lab provider to provide lab home services, and to top it off we have recently launched a premium appointment service that partners with 500+ hospitals that allow patients to book a doctor appointment inside our application. We are extremely fortunate to be trusted by our investors, such as the Bill & Melinda Gates Foundation, Singtel, UOB Ventures, Allianz, GoJek, Astra, Temasek and many more. We recently closed our Series C round and In total have raised around USD$180 million for our mission. Our team works tirelessly to make sure that we create the best healthcare solution personalised for all of our patient's needs, and are continuously on a path to simplify healthcare for Indonesia.