Android — Compound View

Tram Ho

In this article, I will talk about compound view in Android.

  • What is a compound view?
  • What are the advantages of using it?
  • How to write one?

I will answer this question by writing a simple compound view that displays rankings from social networks.

What is a compound view?

Compound view is basically a ViewGround with predefined actions and a set of View inside it. In this example, the compound view is a LinearLayout with 3 internal TextViews, animation and fadeIn effect.

What are the advantages of a compound view?

  • Packaging and centralized logic processing.
  • Avoid code duplication.
  • Easy to maintain and modify in the future.

Writing a compound view

Imagine your app showing your app’s favorite scores and POIs that have ratings linked from different sources, you will show ratings in many places, POIs can have Facebook ratings but is not Foursquare and in the future we may have new ranking sources.

Using compound view, I can encapsulate all this logic and can easily change it in the future if needed.

XML Layout

This is the XML layout file I’m using to inflate into LinearLayout, note merge This is an important component, the merge tag is a way to avoid redundant ViewGroup, in other words, if we inflate this into LinearLayout, we would not use LinearLayout parent in XML, otherwise we will eventually have 2 LinearLayout, 1 of which is not necessary.

Do not use merge

  • LinearLayout -> LinearLayout -> 3 TextViews

Use merge

  • LinearLayout -> 3 TextViews


The init () method is where the logic occurs, they inflate into the XML layout and pass “this” to the third parameter, the View inflates will be added as children of LinearLayout. Then I set visibility to views as gone and add simple animation fadeIn .

setPOI () takes a POI object and sets the view to display the rank available for that POI. And that, I know there’s a compound view that I can use everywhere in my application.

You can see that this avoids logical duplication every time I want to show the rating, if I need to add a new rating, I just need to change it in the RatingsView class to avoid code duplication.


Share the news now

Source : Viblo