Home

Sunday 17 April 2016

Android Relative Layout vs Linear Layout

Relative Layout has been in use a lot due the ease and quick implementation of Android UI layout. But it comes with a great loss. The way the Relative Layout works is "it measures each child twice". What does the mean?
To explain this lets understand via code :


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<TextView 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="Sample Text"/>

</RelativeLayout>


Here the TextView would be measured twice while processing your UI during runtime which would take more time to display.
Now if you have a complex view hierarchy this would take up a lot of time just measuring. And it can go worse if Nested Relative Layout is used, the already twice measured child of inner Relative Layout would be again measured twice by outer Relative Layout which becomes 4 times just for one view!
So Linear Layout should preferred over Relative Layout!
Also if you use weight_sum attribute within Linear Layout it would again "measure the child twice". So avoid using this attribute as much as possible.

With such restrictions it becomes challenging sometimes to implement complex layouts but the application performance matters too, so let's be balanced next time we make a layout.