Creating a Compound View in Android

Introduction

Often, when developing Android applications, groups of views tend to be used in multiple places. In order to make things easier, it is considered good practice to encapsulate them in a custom compound view. This allows the same custom view component to be reused throughout the app.

A compound view or compound component is just a view composed of a group of views. This tutorial focuses on building a very basic compound view and defining some methods that change its state.

Creating the Compound View

Creating a Compound View is, in some respects, somewhat similar to creating a new Activity. A new class is created which contains all the view’s children and some methods to manipulate them.

To get started, we’ll first create a new XML layout file in /res/layout/view_article.xml. This will contain the compound view’s children:

Next, we need a class to inflate our new Article View. For simplicity’s sake, we’ll extend a basic RelativeLayout and define our child components. When the view is added to an Activity, it will basically act as a RelativeLayout and allow developers to customize it accordingly.

It is considered best practice to handle the instantiation of our UI components in the onFinishInflate() method in order to prevent any NullPointerExceptions, especially when using ImageViews with large Bitmaps.

At this point, our new Article View doesn’t really do anything special except displaying its children components. As a result, we’ll add some custom methods to manipulate its states:

Finally

Now that the ArticleView is complete, we just need to add it to an Activity. We will first add it to the Activity’s layout XML file:

Finally, we initialize it in the Activity and make use of it’s methods in order to change the ArticleView’s state:

 

Get the full sample project here.

 

Share this on:

Leave a Reply

Your email address will not be published.