How to make a custom view

Pierce Zaifman
AndroidPub
Published in
2 min readApr 15, 2017

--

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:

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:

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.

If You Enjoyed Reading, Please Click That Little Heart. If You Want To Read More Like This, Follow Me On Medium. Thanks!

Originally published at piercezaifman.com on April 15, 2017.

--

--

Pierce Zaifman
AndroidPub

Freelance Android app developer | I love productivity, creativity, and finding balance | Email me for a quote at pierce@piercezaifman.com