Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


Share this Page URL
Help

Chapter 4: Object-Oriented Programming i... > Classes That Must (And Must Not) Be ... - Pg. 201

Classes That Must (And Must Not) Be Extended 201 (android.graphics.Color.GRAY); } } The earlier section starts with a question: "In the onClick method, how does the code know what button means?" In this section, that question goes away just as my lap goes away when I stand up. In Listing 4-4, both the button and the onClick method are members inside the activity. So the onClick method has free and easy access to the button. You don't need an Activity field as in Listing 4-4, and you don't need any fancy casting from Activity to MyActivity. You have to remind Android that MyActivity contains an onClick method; you do that by adding implements OnClickListener to the dec- laration of MyActivity. You must also remind Android to notify the current MyActivity object whenever the button gets clicked. You do this remind- ing by writing button.setOnClickListener(this); Book II Chapter 4 Object-Oriented Programming in Java which, roughly speaking, translates to "Hey, Android! When someone clicks the button, call the onClick method that's inside this object (a MyActivity object, which fortunately implements OnClickListener)." The pattern in Listing 4-4 (having an Activity implement whatever inter- face it requires) is a very common Java programming idiom. Classes That Must (And Must Not) Be Extended If a Java class isn't broken, don't fix it. Suppose you want to add functionality to an existing Java class. You like Android's Activity class, but the predeclared Activity class displays nothing on the screen. Do you rewrite Android's Activity class? No. Instead of rewriting an existing class, you extend the class. Even in a do-nothing Android "Hello" application, you write public class MyActivity extends Activity Then, in the MyActivity class's declaration, you write @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); }