1. Introduction to ViewGroup

A ViewGroup in Android a special view that can contain other Views. A ViewGroup can contain one or multiple child. All other standard layout managers such as LinearLayout, FrameLayout, RelativeLayout are specialized sub classes of ViewGroup class that layout their child in specific format. For example, LinearLayout layout its child one adjacent to other either vertically or horizontally.

Sometimes, due to specific nature of requirement, the standard layout managers are not enough. You need to extend the ViewGroup class to create your own custom layout manager.

This post will help you to deal with creating a custom Layout manager class TagLayout that will be used to display the list of tags as shown in the following screenshot.

Create Custom Layout in Android by Extending ViewGroup Class

You have to perform the following steps while creating custom Layout manager.

  1. Extend your class from ViewGroup class.
  2. You must override the onLayout() method. This method is used to place child views.
  3. Override onMeasure() method. The onMeasure() method will be used to for parent to determine the size of the view group based on calculating the child view size.
  4. The onMeasure() and onLayout() method, will contain the logic to organize the child views with in parent layout.

You can measure each of the child view height and width by calling getMeasuredWidth() and getMeasuredHeight() methods.

2. Creating Custom ViewGroup

public class TagLayout extends ViewGroup {
    int deviceWidth;

    public TagLayout(Context context) {
        this(context, null, 0);

    public TagLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);

    public TagLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

    private void init(Context context) {
        final Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        Point deviceDisplay = new Point();
        deviceWidth = deviceDisplay.x;

    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        final int count = getChildCount();
        int curWidth, curHeight, curLeft, curTop, maxHeight;

        //get the available size of child view
        final int childLeft = this.getPaddingLeft();
        final int childTop = this.getPaddingTop();
        final int childRight = this.getMeasuredWidth() - this.getPaddingRight();
        final int childBottom = this.getMeasuredHeight() - this.getPaddingBottom();
        final int childWidth = childRight - childLeft;
        final int childHeight = childBottom - childTop;

        maxHeight = 0;
        curLeft = childLeft;
        curTop = childTop;

        for (int i = 0; i < count; i++) {
            View child = getChildAt(i);

            if (child.getVisibility() == GONE)

            //Get the maximum size of the child
            child.measure(MeasureSpec.makeMeasureSpec(childWidth, MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(childHeight, MeasureSpec.AT_MOST));
            curWidth = child.getMeasuredWidth();
            curHeight = child.getMeasuredHeight();
            //wrap is reach to the end
            if (curLeft + curWidth >= childRight) {
                curLeft = childLeft;
                curTop += maxHeight;
                maxHeight = 0;
            //do the layout
            child.layout(curLeft, curTop, curLeft + curWidth, curTop + curHeight);
            //store the max height
            if (maxHeight < curHeight)
                maxHeight = curHeight;
            curLeft += curWidth;

    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int count = getChildCount();
        // Measurement will ultimately be computing these values.
        int maxHeight = 0;
        int maxWidth = 0;
        int childState = 0;
        int mLeftWidth = 0;
        int rowCount = 0;

        // Iterate through all children, measuring them and computing our dimensions
        // from their size.
        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);

            if (child.getVisibility() == GONE)

            // Measure the child.
            measureChild(child, widthMeasureSpec, heightMeasureSpec);
            maxWidth += Math.max(maxWidth, child.getMeasuredWidth());
            mLeftWidth += child.getMeasuredWidth();

            if ((mLeftWidth / deviceWidth) > rowCount) {
                maxHeight += child.getMeasuredHeight();
            } else {
                maxHeight = Math.max(maxHeight, child.getMeasuredHeight());
            childState = combineMeasuredStates(childState, child.getMeasuredState());

        // Check against our minimum height and width
        maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());
        maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());

        // Report our final dimensions.
        setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
                resolveSizeAndState(maxHeight, heightMeasureSpec, childState << MEASURED_HEIGHT_STATE_SHIFT));

3. Add Custom ViewGroup on Activity Layout

Now that we are ready with the view group, let us add it to the activity layout.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"



4. Define Child View Layout

You may have notice from the layout above, we will create custom layout for view group child. In this case the tag item.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

        android:textColor="#fff" />


5. Adding Child View to Custom ViewGroup

Here is what it goes in my activity. For the sake of simplicity, I am inflating 20 child views from inside for loop. You may have some complex logic to get the data from some other source.

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    protected void onCreate(Bundle savedInstanceState) {

        TagLayout tagLayout = (TagLayout) findViewById(R.id.tagLayout);
        LayoutInflater layoutInflater = getLayoutInflater();
        String tag;
        for (int i = 0; i <= 20; i++) {
            tag = "#tag" + i;
            View tagView = layoutInflater.inflate(R.layout.tag_layout, null, false);

            TextView tagTextView = (TextView) tagView.findViewById(R.id.tagTextView);


This article is about: Custom View,


A blogger, a bit of tech freak and a software developer. He is a thought leader in the fusion of design and mobile technologies. He is the author of Xamarin Mobile Application Development for Android Book (goo.gl/qUZ0XV3), DZone MVB and founder of stacktips.com.


Please note: We reserve the right to delete comments that contains snarky remarks, offensive or off-topic. To know more read our comments policy.
  • Madhan Cena

    Can u plz help me how to set the gravity is center to the tag layout

  • Jeffrey Liu

    This is not a very reliable code, when i add a lot of tags the tags doesn’t appear right away.

  • one thing to be noted in the onMeasure with the line
    maxWidth += Math.max(maxWidth, child.getMeasuredWidth());

    which will make the ViewGroup to have its width doubled with each child inserted. For me, if I have number of Tags (or child views in this view group) greater that 23, it won’t be shown. For me, I solved this issue by having

    maxWidth = child.getMeasuredWidth();

    besides, this ViewGroup didn’t take into account if the layout direction was from right-to-left (RTL), e.g. Arabic, Hebrew, etc…

    And finally, thanks a lot for this tutorial.

    • Thanks for your comments. Will update the tutorial accordingly.

      • Xiangdong

        Source code on github wasn’t updated. Thanks~

    • Xiangdong

      Where this piece of code is: maxWidth = child.getMeasuredWidth();