How to make a custom view

Android provides you with a bunch of common views and ways to modify them. Sometimes you need to set a few of the same properties on the same types of views throughout your app. In that case you could make a layout and use the include tag to include it in every layout you need it in. So you can re-use it wherever you need it.

That may be fine, but what if you want to change a property on that view in one place it’s included? For example, you want to change the text colour of a TextView inside that layout. Since it’s in the included layout, you can either change it for every place it’s used or you have to do it programmatically. You can’t set it through the include tag.

To solve this problem, you can create a custom view by extending one of the existing views.

Example

To demonstrate this, I created an example custom view. It extends from LinearLayout and has two TextViews inside of it.

I could have added the TextViews programmatically, but I prefer to have a layout inflated instead. You can see the layout below:

I use the merge tag so the layout can be inflated directly into my view, which is a LinearLayout.

In my CustomView layout I have TextViews for a title and subtitle. I want to be able to set these in any layout where they are included, so I have to add custom attributes in my attrs.xml file.

Now to actually use this view, I created an example activity which adds my view to its layout.

The result looks looks like this:
result

I had included checks to make sure the title and subtitle were included, throwing an exception otherwise. If they aren’t included, the renderer will not display the views and shows the appropriate exception. For example, if I forgot to set the subtitle I will see this exception:
error

The standard views provided by Android are usually enough to solve most problems. But, if they are lacking or you find you’re often duplicating layouts, consider making a custom view. It may save you some time.

Pierce Zaifman

Android app developer. Hates wasting time and takes satisfaction in improving efficiency in all aspects of life. Also enjoys helping people solve their problems.

London, Ontario, Canada

Subscribe to Pierce Zaifman

Get the latest posts delivered right to your inbox.

or subscribe via RSS.