Boost your Android productivity — Use Compound ViewGroups

Romit Choudhary
Published in
3 min readOct 11, 2017


You must be thinking, What is a Compound ViewGroup now?

If not, then good you already know what it is.

if yes, then let me tell you what it is.

A Compound ViewGroup is nothing but a reusable group of views bundled together inside an Android ViewGroup (such as LinearLayout, RelativeLayout etc.), which can be treated as a single thing.

Combination of EditText and Button

For e.g.

A combination of an EditText field and a Submit Button.

The button is only active when the EditText is non empty.

So, in this case you can easily abstract out the logic of enabling/disabling the Button and resuse this component in different parts of the app.

Advantages of using a Compound ViewGroup :

  • Abstraction of code
  • Reusable components
  • Quickly construct arbitrarily complex compound views and re-use them as if they were a single component
  • Define your own interactions (click listeners and others)

Since now you got an idea of what a Compound ViewGroup is. Let’s create one! We’ll be creating a compound view for Rating stars.

So, our RatingView will extend a LinearLayout, and the children of this LinearLayout will be multiple CheckBoxes (Our star background checkboxes)

Since our RatingView can have any number of stars, we will be adding the CheckBoxes view dynamically inside the init() method of

Based on the number of ratingStars obtained from xml attributes or default which is 5 in our view, we will inflate those stars from rating_star_item.xml and add it to the LinearLayout inside

What do we need to create this Compound View?

  • A Checkbox xml with custom background; rating_star_item.xml, rate_app_checkbox_background.xml
  • Star drawables; both filled and empty
  • Styleable attrs in attrs.xml for custom attributes; such as numStars, rating; to change layout from XML only
  • A RatingView class to define our methods for view initialization and bindings;

The different public methods provided by the view are:

  • setRating(int rating): Changes the rating of the view programatically
  • getRating() : Returns the current rating of the view.
  • setRatingListener(OnRateListner onRateListener): Sets a listener to receive a callback whenever the rating is changed.
  • setIsRatingAllowed(boolean isRatingAllowed): Enables/disables rating click interactions

And we’re done! Now to use this anywhere in your project, just add it to XML like this:

That’s all for this post! Will keep posting interesting snippets about Android and other things. Follow me to get updates :)

Thanks for reading this article. Be sure to clap/recommend as much as you can and also share with your friends. It means a lot to me.