Android Adventures - Basic Controls And Events
Android Adventures - Basic Controls And Events
Written by Mike James   
Tuesday, 03 March 2015
Article Index
Android Adventures - Basic Controls And Events
Basic Input Controls
Three Buttons
Checkboxes

 

Two More Ways To Handle An Event

To avoid the overheads you can use one of two possible methods. 

  • implement the interface in the activity. 
  • use an anonymous class

The first is something of "clever fix" and it relies on the fact that any class including your Activity can implement an interface. The second is based on the use of an anonymous class which is a language feature that was introduced to Java specifically to help with the need to create an instance of a class without having to actually create a class file or even give the class a name. 

Of the two the anonymous class is probably the best way to go about things but you will see both used in other peoples code and code examples so you need to know about both. 

Implement the interface in the activity

One, almost cheats way, of doing things is to simply use the MainActivity class to implement the event listener interface. After all you can specify any class as an event handler as long as it implements the correct interface. It doesn't matter to the event mechanism that the class also implements lots of other methods that have nothing to do with events. 

This seems a little strange when you first see it but it is the closest approach to the way other languages do the job.

For example, to handle the onClick event we need to add the "implements" for the interface to the Activity: 

public class MainActivity extends AppCompatActivity 
    implements View.OnClickListener {

Now all that has to happen is that the Activity class has to implement the onClick event handler. Don't worry about the fact that the line has a read underlining indicating an error - the error is that you have to implement the method. To do this place the cursor in implements and use alt enter to display a menu of options that includes implement methods.

implements

If you select this you can select the methods you want to implement and Android Studio will add them to your code. In this case we just want to implement onClick:

@Override
public void onClick(View view) {
//Handle Event
}

All that remains is to add the event listener using setOnClickEventListener but what is the instance of the class that is providing the event handler?

If you recall what happens is that the system creates an instance of the MainActivity class to get your app running and the current instance of a class is always "this". So we need to add to the onCreate method:

button.setOnClickListener(this);

In many ways this last way of doing things is the simplest.

It has the disadvantage that you have to add an "implements" for each event you are going to handle but this could be an advantage in that it enables you to see what events are being used.

Also notice that using this method you set all of the event handlers using

somecontrol.setOnSomeEvent(this);

This also implies that you will be using the same event handler for an event irrespective of which control generated the event. That is you will write a single onClick function and this will be used for all of the controls that you use setOnClickEvent(this) on.

If you want to use multiple event handlers - one for each control then you need to use the anonymous class approach.

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. The only down side 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.

In the case of an event handler you can take an interface and implement it as 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 section.  

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.

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. 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 at the moment 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. 

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. 

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. 

The Basic Input Controls

Now that we have discovered how events work it is time to take a look at the most commonly used input controls.

The term control comes from the idea that the user "controls" your program using them - widget or GUI component are also terms that are used to mean the same thing.

The basic input controls are:

  • Buttons
  • Text Fields
  • Checkboxes
  • Radio Buttons
  • Toggle Buttons

If you have programmed using other UI frameworks many of these will be known to you and you can probably skip to just the ones that interest you.

Starting right at the beginning however let's revisit the Button but in a little more detail

Buttons

There are two basic types of button - Button and ImageButton - but the Android Studio Toolbox has three Button, Small Button and ImageButton.

Small Button is just a standard Button control but with a style applied to make the font smaller and hence more suitable for a small button.

The ImageButton is much the same as the Button but it has a src property which can be set to an image which will be displayed as the button icon and it doesn't display any text. 

The main properties that you work with in the case of a button is are things like background - which can be set to a color or a graphic. You can spend a long time changing the way buttons look but in the main the only important property of a button is its onclick handler.

A button is in your UI to be clicked. 

If you place one example of a Button, Small Button and ImageButton on the design surface you can use the properties window to customize them.

Set the Background of the Button to dark grey by clicking on the ellipsis at the right of the property and then selecting the System tab in the Resource browser that appears. Scroll down and you will see a set of predefined colors that you can use. Find background_material_light and select it.

colors

 

For the small button set the Background property to a drawable in the same way - i.e. select "drawables" in the left-hand menu scroll down in the Resource browser until you see items starting ic then select ic_menu_add.

We will discuss the use of resources and drawables in a later chapter. For now just assume that they are styles and graphics elements that you can select.

drawable

 

Repeat the task for the ImageButton but set the src property to ic_menu_add. 

 

The result is the three buttons shown in the image below:

buttons

 

You can spend a great deal of time exploring ways to make use of a button's properties to style it just as you want it to look. 



Last Updated ( Thursday, 28 April 2016 )
 
 

   
Banner
Copyright © 2016 i-programmer.info. All Rights Reserved.
Joomla! is Free Software released under the GNU/GPL License.