ZOFTINO.COM

Android User Interface Layouts

Android app user interface can be defined either in xml or in code. Android UI consists of hierarchy of views and view groups.

View is the base class for all UI components like button, check box, and text fields.

ViewGroup, subclass of View, is the base class for container views like list view, recycler view, and grid view and layouts like linear layout, relative layout and grid layout.

ViewGroups are not visible; they are containers and hold other views in the UI. With view groups, you can position UI components on the screen as per your requirements. The root of the android UI view hierarchy is view group.

In this article, I am going write about layouts and ways to improve the performance of and to optimize the layouts.

Here one point that needs to be noticed is that the entire UI definition for screen is called layout and the view group subclasses which position views in it are called layouts (layout classes) also.

Defining Layout

You can define UI for your activity in xml file and place it in layout resource folder. Below is an example.

 

    

    

Setting Layout for Activity and Modifying Views in Code

Once layout is defined, you can set it as UI for an activity. You can do so by calling setContentView method passing layout file name in activity’s onCreate() method.

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_constraint);
}

You can modify views by finding the view using findViewById method in the activity.

        TextView tv = (TextView)findViewById(R.id.search_text);
        tv.setText("search");

Android Layout Drawing Process

Android framework starts the process of drawing layout for an activity when the activity gets focus. The drawing process involves three passes, initialization, layout and drawing pass.

In initialization phase, all view classes are instantiated with user supplied property values.

There are two parts in layout phase. In the first part, android framework traverses through view hierarchy top-down and sets measurements like width and height for each view. In the second part, it traverses through view hierarchy top-down again and positions each view in its parent using measurements calculated in the previous step.

In drawing pass, views are drawn on screen, first parents and then children.

Android Layouts

Android framework provides several layout classes and view groups which allow you to display views in different positional ways on the screen. Some layouts allow you to display views in a particular pattern like displaying all views on the screen horizontally, vertically, or grid style. Some layouts give full control so that views in those layouts can be aligned however you want.

There are two main problems with layouts in android, performance related and alignment related issues. Performance issues occur due to nesting layout and alignment issues occur due to lack of support for aligning views on both axis. To solve these problems, android provided different layouts. First I’ll give brief information about those layouts with examples and then I’ll talk about ways to improve the performance and to do the optimization of layouts.

Linear Layout

Linear layout displays views horizontally or vertically. The attribute of linear layout that controls orientation is android:orientation, set it to either horizontally or vertically.

Relative Layout

Relative layout allows you to display views relative to parent or sibling views. For example, you can make a view display below another view or align center within parent.

Nesting layouts has huge impact on UI performance. With relative layout, you can reduce number of nested layouts and there by improve your UI performance.

If a view’s visibility is set to GONE, then other view which depends on the GONE view for alignment can’t be positioned as relative layout does not know exactly where to position the view. To fix this problem, you need to set alignWithParentIfMissing to true to tell the relative layout that in case of missing views, align positional-dependent views to parent.

 

    

    
    


GridLayout

GridLayout was introduced to solve the problem of inability to align the views both horizontally and vertically. This type of alignment can’t be achieved with leaner layout.

With grid layout, you can align views both horizontally and vertically. You can achieve grid type of display using relative layout. But relative layout is slow compared to simple grid layout, grid layout without nesting. If you can’t avoid nesting of layouts, then go for relative layout.

 

    
    
    
    
    
    

Frame Layout

To display views overlapped or to display views one on another, you can use frame layout. Frame layout’s child view’s position can be controlled with layout_gravity attribute.



    

    

frame layout example

Coordinator Layout

Coordinator layout allows child view to interact with other child views, or parent. For this, you need to define Behavior for each view that needs to provide certain behavior in response to certain events, or changes to dependent views. Coordinator layout executes the supplied behavior in response to certain events or dependent view changes.

For more information on coordinator layout, you can read my post coordinator layout and custom behavior.

Swipe Refresh Layout

With swipe refresh layout, you can easily implement screen refresh functionality. Meaning, content can be refreshed using swipe refresh layout when user makes vertical swipe gesture. Swipe refresh layout detects the refresh gesture and notifies the listener registered by the screen activity. It is listener’s responsibility to get the latest content and refreshes the screen with it.

Sliding Pane Layout

Sliding pane layout is a two pane layout. If you have content that suits the scenario of displaying list of items in one pane, and details of each item in different pane, then go for sliding pane layout. With the sliding pane layout, you can achieve the behavior of showing both the panes on the large screens, and collapsing the list pane and showing only details pane on the small screens. The closed pane can be dragged to open it.



    
    

sliding pane layout example

Constraint Layout

Constraint layout is similar to relative layout, both layouts allow you to position child views relative to each other or parent, and flatten the view hierarchy meaning reduce the depth of hierarchy to improve the UI performance.

But constraint layout is flexible and easy to design layouts using android studio layout editor. Below is the constraint layout example which gives the same UI output as the above relative layout example gives.

constraint layout example
 


    

    

    

 

Layout Performance

App performance gets impacted if you choose wrong layouts. To improve UI performance, you need to optimize layouts with help of tools which I talked about in the next section below. But following below best practices can help you achieve well performing UI.

Nesting layout decreases performance. So in order to reduce nesting, it is better to use relative layout or constraint layout.

Nested liner layout with width parameter makes it more expensive as measure pass happens twice.

If you have a group of views repeatedly used across many screens in your app, it is better to separate them and create a separate layout file that can be included in main layout files. But in the process of increasing reusability of layouts, one common mistake that many of us make is to introduce unnecessary nested layout by using layout class as root element.

To prevent this unnecessary nesting, use merge element as root in the layout files which are included in the main layout files.

Creating complex views definitely impact the performance of UI. So it is good practice to reduce clutter to not only improve performance but also the user experience. Instead of keep number of views on one screen, move section of UI element to different screen or provide options menu.

Using tabs introduces three levels to your view hierarchy so it is better to avoid it.

When you use list view, make sure that processing like fetching data, loading images, and network access is performed in the background thread so that you will achieve smooth scroll experience.

It is a good practice to use view holders, which holds references to views, to reduce the number of findViewById() calls as this call is expensive.

Delayed Loading of Views

If there are resource intensive and rarely used complex views in your layout, it is better to defer loading them when they are needed.

You can accomplish the feature of delayed loading of views by defining ViewStub. ViewStub is lightweight, a zero dimensions view and not expensive to inflate.

In ViewStub definition, you need to set attribute android:layout to target layout xml and attribute android:inflatedId to the id to be assigned to root view of target layout.

When target layout needs to be displayed, you need to call inflate on view stub.

Optimizing Layouts

To optimize layouts in your app, you can use android device monitor tool which comes with android SDK. You can open android device monitor in android studio by going to Tools > Android and clicking Android Device Monitor. To open hierarchy view in android device monitor, go to windows > open perspective then select hierarchy view. Hierarchy view in android device monitor is what we need to optimize layouts.

But to view hierarchy structure of current activity layout, first you need to run your app on emulator, or on USB connected device and then open android device monitor, while opening android device monitor disable-ADB-integration window appears. You need to click yes in order to open the android device monitor.

Open hierarchy view in the android device monitor, then in the tree view, you can select node to see measure, layout, and draw times. You can also view times for all tree nodes under a selected node.

Three dots are shown for each view for all views under the selected node. Three dots represent performance of the view during three phases, measure, and layout and draw respectively. Here the performance is relative to other node. You need to analyze red node as they are potential problem nodes.

You can use lint tool also for finding performance and other issues with layouts. You can run lint tool from android studio by clicking analyze > inspect code.