Pages

Wednesday, February 27, 2013

Creating Custom Views on Android - A Beginner's Tutorial

Now that you've mastered the art of using the Android canvas and can use a fragment like nobody's business, you're going to want to put something pretty on that fragment. But what if what you want to put on that fragment isn't in the Android SDK? That's where custom views come in.

Creating the Class

In order to incorporate your custom view into your application at all, you will first need to create a class that extends  the existing Android View class. In this tutorial, we will be extending the View class.

First, you must create the class file, give it a name, and extend the View class.

As you can see, its a very blank file. We will fill it up later, but let me explain what is in the above file: there are two constructor methods provided in the class, both of which look very similar. Why include both of these? The first is for if you ever want to include it manually in code without any layout attributes. But if you want to include the custom view in a layout XML file, you need the second one. That is something we will be doing later in this tutorial.

Drawing the View

Now that you have a shell of a class, you need to actually do something with the view you have. To do this, you must override the onDraw method of the CustomView class.



As you can see, we now have to actually draw something in this method. That's easy! You've already learned how to play with the canvas in my other tutorial. For the sake of this tutorial, I'm just going to draw a rectangle at the center of the canvas like so:


The last thing that we must do is add the view to our Activity.

Adding the View to your Activity

This is one of the easiest parts. Its just like adding any old view! Find the class's package and class name, and insert it like any other view:


And you're done! Now go out there and make some Views!

No comments:

Post a Comment