Lesson 9. Button event handlers.

Lesson 9. Button event handlers.


In this lesson we:

– learn how to handle the button and learn what a handler is

Let’s create a project:

Project name: P0091_OnClickButtons
Build Target: Android 2.3.3
Application name: OnClickButtons
Package name: ru.startandroid.develop.onclickbuttons
Create Activity: MainActivity

In the layout file main.xml write the following and save:



    
        
        
        
        
    
 

We have a TextView with text and two buttons: OK and Cancel. We’ll make TextView content change when you click it. When OK is pressed – we will display the text: “OK button pressed”, after pressing Cancel – “Cancel button pressed”.

open MainActivity.java. The description of objects will be taken outside the method onCreate. This is so that we can access them by any method. At onCreate, we will fill these objects using the method we have already passed findViewById. The result should be:

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);

    }
}

We are updating the import section (CTRL + SHIFT + O). The tvOut, btnOk, and btnCancel objects match the View elements of the screen and we can handle them. We need to teach the button to respond to clicks. To do this, the buttons have the setOnClickListener method (View.OnClickListener l). An object with the View.OnClickListener interface is fed to the input. It is this object that the button instructs to process the click. Let’s create such an object. We continue to write the code in onCreate:

    OnClickListener oclBtnOk = new OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

        }
    };

Eclipse highlights the OnClickListener with a red line

so he doesn’t know him yet. The import section needs to be updated. Pressing CTRL + SHIFT + O, Eclipse shows us that it knows two interfaces named onClickListener and offers to choose. We need View.OnClickListener because the setOnClickListener button method accepts it.

So we created an oclBtnOk object that implements the View.OnClickListener interface. The object contains the onClick method – this is just what we need. This method will be called when a button is pressed. We decided that after clicking we would output the text: “OK button clicked” in TextView (tvOut). We are implementing this.

In the onClick method we write:

tvOut.setText("Нажата кнопка ОК");

The click handler is ready. It remains to “feed” his button using the setOnClickListener method.

btnOk.setOnClickListener(oclBtnOk);

The result should be the following code:

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 oclBtnOk = new OnClickListener() {
            @Override
            public void onClick(View v) {
                // Меняем текст в TextView (tvOut)
                tvOut.setText("Нажата кнопка ОК");
            }
        };

        // присвоим обработчик кнопке OK (btnOk)
        btnOk.setOnClickListener(oclBtnOk);
    }
}

We save and run everything. Click on the OK button and see. That the text has changed

Clicking Cancel does not lead to anything, because we did not create or assign a handler for it. Let’s do it the same way as for the OK button. We first create a handler:

        OnClickListener oclBtnCancel = new OnClickListener() {
            @Override
            public void onClick(View v) {
                // Меняем текст в TextView (tvOut)
                tvOut.setText("Нажата кнопка Cancel");
            }
        };

Then we assign it to the button:

btnCancel.setOnClickListener(oclBtnCancel);

Save, run, check. Both buttons are now able to handle pressing.

Let’s talk about the event handling mechanism once again, with the click of a button. The button itself cannot handle pressing, it needs a handler (also called a listener listener), which is assigned using the setOnClickListener method. When the button is clicked, the handler responds and executes the code using the onClick method. This can be depicted as:

Accordingly, the following steps are required for implementation:

– create a handler
– fill in the onClick method
– assign a button handler

and the event processing system is ready.

In the next lesson:

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




Discuss in the forum [402 replies]

Leave a Comment