Custom Views In Android

Rachit Goyal
Technology at upGrad
8 min readNov 13, 2017

--

Writing code for custom views can be tricky business. But making the decision to write custom views or go with default ones is a bigger dilemma.

Occasionally, when required to build a complex layout, we get to a point where we find ourselves at a clear crossroads. We are faced with two options, and choosing one is never easy.

One option is lucrative - easier to code, and quite possibly faster. This route requires using a bunch of default android views.

The other route looks more complex - requiring more coding prowess, taking up more time and seeming more difficult. This is the route of writing your own, custom views.

As you stand at this decision junction, the first route might seem like the logical choice, after all, time is an extremely valuable resource, and if you can do something in a simple manner, why wouldn’t you? Moreover, a lot of confusion and fear revolves around building custom views.

I’m going to discuss the pros and cons of each option here, in the hope that it will help you make a more informed and logical decision on which path to take.

Let’s handle the two most important questions here — Why and Why not?

Why should you use custom views? and Why should you not use custom views?

Why should you use custom views?

Or as I like to call it, the pros of writing custom views.

1. Code Readability

So let’s take an example scenario, one that I was actually faced with.

I needed to develop a Bar, which would be segmented into sections, and some of those sections would be activated while others remained gray, based on the user progress.

ProgressView

One way to do this was to create multiple Views during Run Time. The code might look something like this:

Using Default Views

And the other option:

Using Custom Views

The second option here looks much cleaner and easier to understand. The major factor to understand here is that the code to generate your views does not belong to your activity. Segregating it makes your code more manageable.

This was a simple example, but with more complex layouts, the code can become very complex and messy, if you do not use custom views.

A counter-argument here can be that I’ve not mentioned the coding that goes into creating the ProgressView class, which will be technically challenging and not easy to achieve. Well, the idea here is not to bypass challenges, but to make the Activity code cleaner, easier to understand and more maintainable.

2. Reusability

When developing large scale apps, code reusability is extremely common. Similar UI components will be used in multiple places very frequently, to maintain a standard user experience across the app. With this in mind, building custom views might eliminate code redundancy in a lot of places.

Once you create a particular custom view, it can be easily used in multiple locations across the app, and also across multiple projects.

Taking the above example of ProgressView, we can now create multiple instances of ProgressView in our app, without needing to write the code to generate multiple views every time. So even though creating a custom view takes more time once, as a whole it might reduce the amount of effort and time needed to develop the application.

Credits: https://hermesespinola.files.wordpress.com/2016/11/repository-component-reusability.png

3. Improved Performance

This might sound counter-intuitive at first, but building custom views can be an effective way to improve your app’s performance. If you’ve written applications with complicated RecyclerViews, then you must have come across the problem where when you scroll on the RecyclerView, you notice a prominent jitter.

How do RecyclerViews work? As you scroll, the app draws each row of the RecyclerView as they come into focus. So if a particular row has a lot of views, then that many iterations need to be made to draw the entire row. The more complicated the layout, the more time is required to do the drawing. And this is what results in the laggy behaviour.

Credits: https://i.pinimg.com/236x/df/76/8e/df768e2d593106017a664a4a11a20e48--snails-alternative.jpg

For such scenarios custom views can come as a great rescue for developers. If you can flatter your hierarchy with a single custom view, you can reduce the drawing process to a single iteration. This can greatly reduce the app’s performance, especially in cases of RecyclerViews or other such lists.

4. Endless Possibilities

Ok, so we can all agree that Android is vast and quite detailed, but there are scenarios wherein the inbuilt features or views of Android are not sufficient for your purposes. Say, for example, you wish to create a ListView wherein you can drag and drop items to rearrange the list ordering. Or you want a Toggle Button with 3 states (Yes/No/Maybe) instead of just 2.

Now, Android views don’t handle such scenarios by default, but that doesn’t necessarily stop you from building something on your own. With a custom view, you can do almost anything. The possibilities are endless.

Just as an example of this you can check out Android Arsenal which has a never ending array of libraries and tools, a lot of which are examples of custom views. If you’re faced with a particular problem and are feeling lazy enough to not want to create your own custom views, Android Arsenal might already have the answer for you.

Why should we NOT use custom views?

We’ve discussed a lot of positives about using Custom Views, but just like everything else they do not come without drawbacks. Let’s take a look at the cons of custom views.

1. Not a piece of cake

So, custom views have pros, we get that. But that doesn’t take away the fact that the developer still needs to write code to create the custom view. And writing custom views is no piece of cake.

To get an idea about what custom views look like, just take a look at any of the popular libraries on github.com.

Credits: https://www.storyblocks.com/images/photos/symbols

The tricky bit is overriding the onLayout() and onMeasure() methods. Even experienced Android developers are rattled when they are required to do so. Here, we won’t delve into how this is actually done, that’s a different discussion in itself, but for the brave souls out there, you can find a lot of resources online that’ll help you on your journey.

This journey might take time, but once you’ve mastered developing your own custom views, the pros start heavily outweighing the cons.

Credits: https://www.electronicsweekly.com/blogs/engineer-in-wonderland/mini-brain-teaser-how-weighing-scales-work-2016-01/

My recommendation here would be to try and experiment with building custom views. It will take a lot of trial and error to get you to perfection, but then again, what doesn’t?

2. Reliable Views

Another major problem with Custom Views is that you need to ensure that you handle everything programmatically. And by everything, I mean EVERYTHING.

If your view is text oriented, you’ll have to ensure the font, text size, color, line spacing, wrapping, shadows, highlight, style and everything else is the way you want it to be. You’ll have to ensure that it renders correctly on all screen densities.

If the view contains images, you’ll have to keep in mind the scaling, aspect ratio, zoom, etc.

You’ll have to ensure the padding, margins, orientation, and so on are maintained properly on all devices.

You’ll have to also handle all kinds of click listeners — single click, double click, long press, swipe and fling.

And not to forget, you’ll have to ensure that the view renders properly on both orientations — portrait and landscape.

I know this sounds scary, and quite possibly could be a major deterrent for you to not choose Custom Views. But to be honest, I made the situation sound a little more grim than it actually is.

For the most part, you won’t have to start from scratch. You can choose one of the existing views, and take that as your base class. For example, if you wish to create a JustifiedTextView (a TextView which renders text which has the justified styling), for such a requirement, you won’t have to do everything in your custom class. You can extend TextView, which will provide you with all the functionalities for TextView. Now all you need to do is render the text so that it is justified. You won’t have to handle click listeners and orientations and many other factors which I mentioned above.

Conclusion

You weren’t born with the ability to speak or walk or understand mathematics (although a lot of people still don’t understand mathematics as adults). You spent a good deal of time and effort to get where you are today. You stumbled many times before you could actually take that first step, but even as an infant that never deterred you from trying again and again.

The same logic applies here.

A lot of people consider Custom Views to be the last resort, to be used only if no other option works, or when the efficiency of the app is not up to the requirements. But in my opinion, custom views are a great way to improve your code, and improve performance at the same time. And if nothing else, it’s a great learning opportunity to understand Android development better. A deep dive into custom view creation will teach you a lot about how to write better code, and improve your grasp of development.

Just don’t be afraid.

Credits: https://www.bleedingcool.com/2017/05/07/new-trailer-lets-air-excitement/

--

--