Tuesday, May 1, 2012

Creating a Custom View That Takes Attributes

This tutorial will demonstrate how to create a custom view that will change its appearance based on a custom attribute set in the xml layout.

1. Custom Attributes

If you have used Android Views in the layout editor, you are probably already familiar with setting attributes for views. For example, for an ImageView you can set the drawable attribute to determine what graphic to draw, or the Text Attribute for a button or label to determine what text will display.

If you find yourself designing a custom view, you may want to add custom attributes to that view that affect the display or behavior. For this example we will build off of the custom view that created before, and add an attribute to change the border color.

2. Defining the Attribute

First, we need to define the attribute for setting the color for the CustomView. We do this by editing a file called attrs.xml that is located in the res->values folder. If you do not have an attrs file, right click on the values folder and select New->Android XML File. Select a type of values, and name it attrs.xml

Creating the attrs.xml file

Once the file is created, open it up to edit the XML.

We will want to edit the XML to add information that defines attributes for our previously created custom view, aptly named CustomView. We will open a "declare-styleable" tag for this custom view. The attrs.xml file should now look like this:

You could define as many attributes as you like, but for this tutorial we will just add one.

3. Updating the Layout File

Next, we want to update the layout file of the project to take advantage of this new attribute. First, we will update the top element LinearLayout to reference the attrs.xml we created by adding the following line.

For fun and extra practice, you could try adding a custom attribute to adjust the thickness of the border.

------------------------------------------------------------

We create these tutorials in our free time. If you like what you see please consider buying us a cup of coffee so we can keep creating useful material. Click on the image below to make a donation via Paypal.