Creating custom views in Android

I will describe the way to implement custom view in Android to get something like this:

Screenshot at Apr 25 11-28-57

and also an approach to add some animation into this view.

So, my task was to create view for showing some kind of chart data. The view should be circular with a few coloured sectors. Some sectors may be drawn as lines with curved edges and some – should fill all ”ring” space.

To implement this task, I’ve created a subclass of View class and added all needed additional methods. First of all, we need to initiate all possible fields during view creation.┬áThis will decrease computational loading during onDraw(). So, on init() method, I’ve prepared all Paint‘s entities for future usage. For custom views we need to calculate real size (in pixel) of the view. This can be done be override onSizeChanged() method:

all future ‘position’ calculations will be based on this values.

During this view creation I haven’t had the data to show (and event didn’t have the format of this data). So, I decided to create simple data with 3 fields:

  • value
  • color
  • boolean – should data fill ‘ring’ or be just like curved line

Next thing we need is applyData method:

Here I’ve converted input data into something that can be easily drawn. All needed calculations are included :). Last thing here is to draw prepared data:

I’ve used drawCircle, drawArc methods to draw all the content. Plus we need some additional simple calculations.

The result is just what we want. Full code example can be found here (master branch).

Leave a Reply