Intro To Android (Workbook 2)

Lab: Custom Views

We'll make a CoverView for reuse in the list view screens as well as the view at the top of the detail screen.

Android's custom view training and the API guide gives you a good start, but stops short of actually implementing the custom view.

Tip: I often create a blank project to work on complex UI components. Working this way reduces the clutter of networking, DB interactions, etc. After I perfect it, it gets copied into my main project.

Steps

  1. Create a custom attributes file called cover_view_attr.xml in the values folder. Create an attribute called showRatingBar that takes a boolean and another called placeHolder that takes a resource. We will add more attributes later. This is not a well documented feature of Android, here's a decent reference and the source.
  2. Create a custom view class called CoverView. Choose a sensible base class.
  3. Add view elements to your view's XML with <merge> tag as the base element in the view.
  4. Add a test class for your custom view. Test that expected view components exist.
  5. Replace the current views in your adapter XML with the new view. Create a namespace and use your new attribute.
  6. Parse the custom attributes in your view and store the XML value in your class. Add getters and setters for the showRatingBar and placeHolder attributes so that users can create an instance of your view either with XML or in code.
  7. Add tests using RoboAttributeSet. Clues here, here, and here. I also asked a stackoverflow question: http://stackoverflow.com/questions/24999471/how-do-i-configure-roboattributeset-for-a-custom-view-in-robolectric.
  8. Inflate your view, use the XML values to configure your view. It will be helpful to break out the view inflation code from your view configuration (which will be based on changing data).
  9. Pass data to your view and use this data to configure the view.
  10. Replace the adapter holder pattern with your custom view. This article will help with this stage.

Homework

Add custom attributes for textColor, textPosition, textBgColor, and pinAnimation. React to these attributes in your view. We'll use the pin animation value when we cover animations.