Update November 2018
Please have a look at my newest library !!
Announcing Bulldog, never use SharedPreferences anymore !!
Never write code like this anymore
In this article i’ll talk about compound views in Android.
- What is a compound view?
- What are the advantages of using it?
- How to write one?
In this article i’m going to answer this questions writing a simple compound view that shows ratings from social networks.
What is a compound view ?
A compound view is a basically a ViewGroup that a predefined behavior and a collection of views inside it. For instance in this example, our compound view is a LinearLayout with 3 TextViews inside, that animates with a fadeIn effect.
What are the advantages of a compound view?
- Encapsulate and centralize logic.
- Avoid code duplication.
- Easier to maintain and modify in the future.
Writing a compound view
Imagine your app shows points of interest and those POI’s have associated ratings from several sources, you will show ratings in more than one place, a POI can have Facebook rating but not Foursquare and in the future we can have a new rating source.
Using a compound view we can encapsulate all this logic and be able to easily change it in the future if necessary.
This is the XML layout we are using to inflate into our LinearLayout, notice the <merge> ? This is an important part, merge tag is a way to avoid redundant ViewGroups, in other words, if we are going to inflate this into a LinearLayout we don’t need to use a LinearLayout parent in XML, otherwise we end up having 2 LinearLayouts, 1 of them unnecessary.
- LinearLayout -> LinearLayout -> 3 TextViews
- LinearLayout -> 3 TextViews
The init() method is where the magic happens, in line 35 we inflate the XML layout and by passing “this” in third parameter the inflated views will be added as children to our LinearLayout. After that we set the views visibility to gone and we add a simple fadeIn animation.
The setPOI() receives a POI object and setups the view to show available ratings for that POI. And that’s it, we know have a compound view that we can use everywhere within our app.
You can see that doing this avoid duplicating the logic every time we want to show ratings, if we need to add a new rating source we only need to change it in RatingsView class avoiding code duplication.