In this post i’m going to cover the basics of what you need to know in order to use custom views efficient in android.
Why custom view
Apart from drawing fancy circles and charts, custom views can save you memory, decrease time in witch your activity displays its content. Enable “show layout bounds” withing developer options and explore your device.
In the Twitter app you can see that part of “twitt view” is custom view. Such approach allows for faster measuring of view leading to faster content.
Compound View – The top level custom view
Most used form of custom view. Compound views are subclasses of containers(relative and linear layout), usually initializing its children and providing API for controlling its state creating reusable component.
Custom Compound View
Unlike compound views we are not subclassing container classes but View Group itself, allowing us to avoid general purpose container layout that are made to handle multiple layout variations. Such approach allows tailoring of positioning/measuring logic to meet our app requirements and skipping multiple measurement of child views. Remember that you don’t need to handle every possible layout combination, just your apps layout.
Also called Flat Views, a direct subclass of the view. It is possible to create complex list view items that are measured in single pass leading to very performant application. Such form of views require a lot of work, everything from positioning and drawing need to be implemented on your own.
Custom views comes at a price. While drawing bitmaps or simple text is easy, more advanced things aren’t. You need to remember that your custom stuff don’t come with platform fancy stuff. Changing every view in your application might be not worth it. Create custom views for parts of your application that are mostly used by its users.
The Basics of Performance
- Don’t draw to much. Drawing 100 000 data points at once will be mostly pointless and will kill your frame rate.
- Don’t draw if don’t need to. User taken finger of your view? Maybe its ok to stop drawing?
- Don’t draw to often. Use “postInvalidateDelayed” to cap drawing at 60 fps.
- Don’t instantiate in onDraw(), re use your variables otherwise GC will block for couple of seconds having to clear thousands of small objects.