Android Adventures - Events
Written by Mike James   
Thursday, 20 October 2016
Article Index
Android Adventures - Events
Implement the interface in the activity
Anonymous Class

Anonymous class

Java has anonymous classes for just the situation we are trying to solve. It lets you effectively create an object, i.e. an instance of a class, without having to explicitly create a class. 

That is a direct method of creating the event object. Instead of 

Event Class -> Event Object -> Set As Listener

we just go straight to 

Event Object -> Set As Listener

The only down side of using anonymous classes is that you can't create a second instance of the class - this is a short cut way of creating one instance of an object.

You create an anonymous class by writing the same code you would need to create an instance of an existing class but you add {block of code} following it to define the new methods of the new class you are creating. The result is an instance of the new class. 

For example suppose you have a class called Hello that displays a hello world message and you want an object that does everything that Hello does but with the addition of a goodbye method. Normally you would create a Leave class that inherits from Hello and defines the new method and then create an instance of Leave. Instead you can write

Hello leave = new Hello(){
  goodbye(){
       display message;
  }
}

This create an instance of Hello that has all of the Hello methods plus the new goodbye method. Notice that leave is an object and not a class and you can call methods such as leave.goodbye() at once. You have avoided having to create a new class just to create one instance of it. If the class you are extending has a constructor that needs parameters simply call the constructor in the usual way and add the code that extends the class immediately after. 

So to create an instance of an anonymous class based on an existing class you simply start off by creating a new instance of the class and then tag on, in curly brackets, all the methods you want to add. 

In the case of an event handler you can take an interface and implement it as if it was a class and create an instance in one go. This is just shorthand, syntactic sugar if you like, for what we did in the previous sections.  

For example:

MyInterface instance=new MyInterface{
  functions which are needed to 
  implement MyInterface
} 

This creates an instance of the implementation of MyInterface that is contained within the braces. No need to define a class to get an instance of it.

So for our onClick event handler using an anonymous class makes things much easier because we don't need a separate file to hold the new class and in fact we don't even need the new class just:

View.OnClickListener Listener=
                    new View.OnClickListener(){
 @Override
 public void onClick(View view) {
  //Implement event handling
 }
}

and the instance of our custom listener complete with our onClick event handler is ready to be used as before:

button.setOnClickListener(Listener);

Of course you can save the use of a variable and simply use the anonymous class in the setOnClickListener as in:

button.setOnClickListener(
                  new View.OnClickListener() {
 @Override
 public void onClick(View view) {

  //Implement event handling
 }
});

We no long have to use the Listener variable but the cost is that we need to be careful to remember to close the function call with a right parenthesis. 

The really good news is that Android Studio will help you create the anonymous class. If you start to type in OnClickListener it will provide you with options to complete the name and you can select OnClickListener - it will then generate dummy functions for all of the methods defined in the interface.

implementmethods

 

All you have to do is provide the code in the body of each of the functions that does what you want. 

There is one small mystery that we have to deal with even though it isn't really useful. Android Studio uses code folding to hide the details of blocks of code from you. Usually this is useful but in the case of anonymous classes it can be confusing. 

For example if you type in the code above that sets the onClickListener then in folded view the code reads: lambda

This is exactly how you would write the same code using a lambda. The point is that, as already mentioned,  you can't use lambdas in Java 7 which is what Android uses. So this way of representing the code is purely for looking at. If you click the small + button to the left you will see the code expand and you will see the full version.

If you could use lambdas in Android code this would be the best way to implement an event handler but you can't and so it is annoying that Android Studio taunts you with this better way of writing an event handler - you will be able to write this in the future and you can write code this way now if you are prepared to do some reconfiguring and give up instant run.

My advice is to write event handlers in one of three traditional ways and wait for lambdas to come to Android Studio. 

Which Approach To Event Handlers Should You Use?

In practice the anonymous class approach seems to be the best because, while it is a little more complicated it is completely general. Using the Activity to implement the interface fails when you need different event handlers linked to each control.

That is, suppose you have three buttons then using anonymous classes you can set a different event handler to each button. If you implement the event handler in the Activity then the same event handler will be used for all three buttons and you code has to test to see which button has been clicked. 

Of course anonymous classes have the opposite problem to implementing the interface in the Activity. You can't reuse the event handler because there is only one instance of it. That is if you want three different event handlers one for each button you have to write out the code three times to create three instances.

The anonymous class approach makes a direct connection between the UI component and the event handling code you are creating. You only have to look at the setListener function call to see the code that handles the event. 

In this sense it is worth the extra effort and  is the one used in the rest of this book. If you want to use the XML method introduced earlier for the onClick event or implement the interface in the activity approach then this should cause no problems.  

Summary

 

  • In Java you can't pass a function to set up an event handler you have to pass an object. 
  • Each type of event has its own interface which is use to create an object which has the methods needed for the event.
  • The most direct way to create an event handler is to create a new class that implements the interface and then create an instance of the class to handle the event. 
  • To avoid the problems with having to create a new class for each event handler Java introduced the anonymous class. You can use an anonymous class to implement an event interface and create an instance of it in one move.
  • Alternatively you can use Activity to implement the interface.
  • At the moment you can't easily use lambda expressions to implement an event handler.

 

 

androidJavaSmallAndroid Programming In Java:
Starting With an App
Third Edition

Is now available in paperback and ebook.

Available from Amazon.

 

 

  1. Getting Started With Android Studio 3
  2. The Activity And The UI
  3. Building The UI and a Calculator App
  4. Android Events
         Extract: Using Lambdas
  5. Basic Controls
  6. Layout Containers
  7. The ConstraintLayout
        Extract: Guidelines and Barriers
  8. UI Graphics A Deep Dive
        Extract: Programming the UI ***NEW
  9. Menus & The Action Bar
  10. Menus, Context & Popup
  11. Resources
  12. Beginning Bitmap Graphics
        Extract: Simple Animation
  13. Staying Alive! Lifecycle & State
  14. Spinners
  15. Pickers
  16. ListView And Adapters

If you are interested in creating custom template also see:

Custom Projects In Android Studio

Androidgears

 

Coming Next

In the next chapter we look at the range of basic UI controls we have to create the typical UI - buttons, textboxes, radio buttons, selections and so on. 

event

To be informed about new articles on I Programmer, install the I Programmer Toolbar, subscribe to the RSS feed, follow us on, Twitter,FacebookGoogle+ or Linkedin,  or sign up for our weekly newsletter.

espbook

 

Comments




or email your comment to: comments@i-programmer.info



Last Updated ( Saturday, 22 October 2016 )