6.8.3. Constructor

Figure 6.9 shows class CannonView’s constructor. When a View is inflated, its constructor is called with a Context and an AttributeSet as arguments. The Context is the Activity that displays the CannonGameFragment containing the CannonView, and the AttributeSet (package android.util) contains the CannonView attribute values that are set in the layout’s XML document. These arguments are passed to the superclass constructor (line 96) to ensure that the custom View is properly configured with the values of any standard View attributes specified in the XML. Line 97 stores a reference to the MainActivity so we can use it at the end of a game to display an AlertDialog from the Activity’s GUI thread.

Get Android™ How to Program, Second Edition 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.