Parameterizing our custom view

We have our custom view that adapts to multiple sizes now; that's good, but what happens if we need another custom view that paints the background blue instead of red? And yellow? We shouldn't have to copy the custom view class for each customization. Luckily, we can set parameters on the XML layout and read them from our custom view:

  1. First, we need to define the type of parameters we will use on our custom view. We've got to create a file called attrs.xml in the res folder:
<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <declare-styleable name="OwnCustomView"> 
        <attr name="fillColor" format="color"/> 
    </declare-styleable> 
</resources> 
  1. Then, we add a different namespace on our layout file where we want ...

Get Building Android UIs with Custom Views now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.