Lesson 10. Optimize the implementation of handlers.
Android Lessons

Lesson 10. Optimize the implementation of handlers.


In this lesson we:

– Learn how to use one handler for multiple View items
– teach Activity to act as a handler

Let’s create a project:
Project name: P0101_Listener
Build Target: Android 2.3.3
Application name: Listener
Package name: ru.startandroid.develop.listener
Create Activity: MainActivity

We will work with the same View as in the previous lesson. code for main.xml:



    
        
        
        
        
    

One handler for two buttons

So we have a TextView with text and two buttons. As in the previous lesson, we will make textView content change when you click the button. When OK is pressed – we will display the text: “OK button pressed”, after pressing Cancel – “Cancel button pressed”. But now we will do it with help one handlerWhich will handle the click for both buttons.

I will remind the mechanism of event processing on the example of a button. The button itself does not know how to handle pressing, it needs a listener, which is assigned using the setOnClickListener method. When the button is clicked, the handler responds and executes the code using the onClick method.

Accordingly, the following steps are required for implementation:
– create a handler
– fill in the onClick method
– assign a button handler

In our case, we will assign one handler to both buttons, and inside the handler will need to determine which button was pressed.

Let’s prepare objects and create a handler:

public class MainActivity extends Activity {
 
   TextView tvOut;
   Button btnOk;
   Button btnCancel;
 
   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.main);
 
     // найдем View-элементы
     tvOut = (TextView) findViewById(R.id.tvOut);
     btnOk = (Button) findViewById(R.id.btnOk);
     btnCancel = (Button) findViewById(R.id.btnCancel);
 
     // создание обработчика
     OnClickListener oclBtn = new OnClickListener() {
       @Override
       public void onClick(View v) {
         // TODO Auto-generated method stub
 
       }
     };
 
   }
 }

Let’s complete the onClick method. A class object is fed to it ViewThis is just what we need. This is the View that was clicked on and which caused the handler. That is, in our case it will be either the OK or Cancel button. We are left to find out ID this one View and compare it with ours R.id.btnOk and R.id.btnCancelTo determine which button it is. To get the ID of any View, the getId method is used. To sort the results, we use the java switch switch.

Implementation of the onClick method:

      public void onClick(View v) {
         // по id определеяем кнопку, вызвавшую этот обработчик
         switch (v.getId()) {
         case R.id.btnOk:
           // кнопка ОК
           tvOut.setText("Нажата кнопка ОК");
           break;
         case R.id.btnCancel:
           // кнопка Cancel
           tvOut.setText("Нажата кнопка Cancel");
           break;
         }
       }

If you run the application now and check it, nothing will happen. We created the handler, but did not assign buttons to it. We assign both buttons to the same handler:

    btnOk.setOnClickListener(oclBtn);
    btnCancel.setOnClickListener(oclBtn);

Now we can run and check, everything should work.

Do you understand one handler can be assigned not two, but any number buttons. And not just buttons. The rest of the View items also have different events that the handlers need. We will continue to work with them in the future. And now it’s important to understand how events are handled.

The difference between the way this lesson is implemented from the last lesson is what we have created now one object handler for both buttons, And in the last lesson – two objects, one for each button. The rule is – the fewer objects you create, the better, because memory is allocated to each object, which is a very limited resource, especially for phones. Therefore, creating a single handler for multiple View is more appropriate in terms of optimization. In addition, the code becomes smaller and easier to read.

There is another way to create a handler that does not need to create objects at all. An already created Activity object will be used

Activity as a handler

The button assigns itself to the handler using the setOnClickListener method (View.OnClickListener l). That is, any object with the View.OnClickListener interface is suitable. Why not have an Activity class like that? We’ll just point out that the Activity class implements the View.OnClickListener interface and populate the onCreate method.

Let’s create a new project for this:
Project name: P0102_ActivityListener
Build Target: Android 2.3.3
Application name: ActivityListener
Package name: en.startandroid.develop.activitylistener
Create Activity: MainActivity

Again, the screen will be the same:



    
        
        
        
        
    

Prepare objects and add implementation implements (implements onClickListener)

public class MainActivity extends Activity implements OnClickListener {
 
   TextView tvOut;
   Button btnOk;
   Button btnCancel;
 
   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.main);
 
     // найдем View-элементы
     tvOut = (TextView) findViewById(R.id.tvOut);
     btnOk = (Button) findViewById(R.id.btnOk);
     btnCancel = (Button) findViewById(R.id.btnCancel);
   }
 }

OnClickListener will be highlighted in red because it is not in import. So CTRL + SHIFT + O and choose View.OnClickListener.

Now Eclipse swears to the MainActivity class. This is because for the class registered interfacebut no implementation of methods of this interface. Let’s fix this with Eclipse. Hover over MainAcivity and select Add unimplemented methods

Eclipse will add a familiar method onClick. Only now this method will be implemented in Activity, not in a separate object-handler. Accordingly, Activity will act as the handler.

We fill the method exactly as before. Nothing changed. He is also fed View (on which the event occurred), by Id we will determine what this View is and perform the following actions:

  public void onClick(View v) {
     // по id определеяем кнопку, вызвавшую этот обработчик
     switch (v.getId()) {
     case R.id.btnOk:
       // кнопка ОК
       tvOut.setText("Нажата кнопка ОК");
       break;
     case R.id.btnCancel:
       // кнопка Cancel
       tvOut.setText("Нажата кнопка Cancel");
       break;
     }
   }

The onCreate method remains to assign a button handler. This will be the object this, that is, the current MainActivity object.

    btnOk.setOnClickListener(this);
    btnCancel.setOnClickListener(this);

With this implementation, we did not create any extra object (Activity is created in any case) and the memory costs are minimal, this is the recommended method. But it may seem complicated and incomprehensible, especially if you have experience in object-oriented programming. In this case, use the implementation that you understand and convenient. And with time and experience, understanding will surely come.

Full Code:

public class MainActivity extends Activity implements OnClickListener {
 
   TextView tvOut;
   Button btnOk;
   Button btnCancel;
 
   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.main);
 
     // найдем View-элементы
     tvOut = (TextView) findViewById(R.id.tvOut);
     btnOk = (Button) findViewById(R.id.btnOk);
     btnCancel = (Button) findViewById(R.id.btnCancel);
 
     // присваиваем обработчик кнопкам
     btnOk.setOnClickListener(this);
     btnCancel.setOnClickListener(this);
   }
 
   @Override
   public void onClick(View v) {
     // по id определеяем кнопку, вызвавшую этот обработчик
     switch (v.getId()) {
     case R.id.btnOk:
       // кнопка ОК
       tvOut.setText("Нажата кнопка ОК");
       break;
     case R.id.btnCancel:
       // кнопка Cancel
       tvOut.setText("Нажата кнопка Cancel");
       break;
     }
   }
 
 }

The simplest implementation of the handler

There is another way of implementation. In the layout file (main.xml) when describing the button we write:

That is, we use the onClick attribute. It specifies the method name from Activity. This method will work when you press a button.

Next, we add this method to Activity (MainActivity.java). Requirements for the method: public, void and login accepts View:

  public void onClickStart(View v) {
    // действия при нажатии на кнопку
  }

The method prescribes the actions you need, and they will be performed at the click of a button.




Discuss in the forum [215 replies]

Leave a Reply

Your email address will not be published. Required fields are marked *