In this lesson we will:

- learn how to process button clicks and find out what a listener is.

Translated by Taras Leskiv (http://android-by-example.blogspot.com/)

 

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 layout file main.xml write the following and save:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="match_parent"
	android:layout_height="match_parent"
	android:orientation="horizontal">
	<LinearLayout
		android:id="@+id/linearLayout1"
		android:layout_width="match_parent"
		android:layout_height="match_parent"
		android:layout_margin="30dp"
		android:orientation="vertical">
		<TextView
			android:id="@+id/tvOut"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:layout_gravity="center_horizontal"
			android:layout_marginBottom="50dp"
			android:text="TextView">
		</TextView>
		<Button
			android:id="@+id/btnOk"
			android:layout_width="100dp"
			android:layout_height="wrap_content"
			android:layout_gravity="center_horizontal"
			android:text="OK">
		</Button>
		<Button
			android:id="@+id/btnCancel"
			android:layout_width="100dp"
			android:layout_height="wrap_content"
			android:layout_gravity="center_horizontal"
			android:text="Cancel">
		</Button>
	</LinearLayout>
</LinearLayout>

We have a TextView with text and two buttons: OK and Cancel. Now we will make the TextView content change when a button is clicked. When OK is clicked - we will display text "Button OK clicked", when Cancel - "Cancel button clicked".

Open MainActivity.java. We will declare instance variables for our objects outside onCreate method. It’s done like this to enable us referencing these variables from any method. We will initialize these object using findViewById method, which we are already familiar with. In the end the resulted code should be like this:

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);
 
     // find View-elements
     tvOut = (TextView) findViewById(R.id.tvOut);
     btnOk = (Button) findViewById(R.id.btnOk);
     btnCancel = (Button) findViewById(R.id.btnCancel);
 
   }
 }

Update the import section (CTRL+SHIFT+O). Objects tvOut, btnOk and btnCancel correspond to View-elements on screen and we can work with them. Now we have to teach buttons to react when it is clicked. To do so setOnClickListener (View.OnClickListener l) method is available. The parameter is an object that implements View.OnClickListener interface. That’s why, the button will delegate click processing to this method. Let’s create such an object. Continue writing code inside onCreate method:

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

 

Eclipse underlines OnClickListener with a red line:

as it is not familiar with it yet. We must update the import section. Press CTRL+SHIFT+O. Eclipse shows us that it knows two interfaces with OnClickListener names and offers us to choose. We need View.OnClickListener, as button method setOnClickListener requires it as a parameter.

 

We have created oclBtnOk object which implements View.OnClickListener interface. This object has onClick method - this is exactly what we need. This is the method, that will be invoked when the button is clicked. We have decided that we will display "Button OK clicked" text in the TextView (tvOut) when the button is clicked. Let’s implement this.

In onClick method write:

tvOut.setText("Button OK clicked");

 

The click listener is ready. The only thing left is to set it to the button using setOnClickListener method.

btnOk.setOnClickListener(oclBtnOk);

 

The resulting 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);
 
     // find View-elements
     tvOut = (TextView) findViewById(R.id.tvOut);
     btnOk = (Button) findViewById(R.id.btnOk);
     btnCancel = (Button) findViewById(R.id.btnCancel);
 
     // create click listener
     OnClickListener oclBtnOk = new OnClickListener() {
       @Override
       public void onClick(View v) {
         // change text of the TextView (tvOut)
         tvOut.setText("Button OK clicked");
       }
     };
 
     // assign click listener to the OK button (btnOK)
     btnOk.setOnClickListener(oclBtnOk);
   }
 }

 

Save and run the application. Click OK button and see that the text has changed.


Clicking Cancel button does nothing for now, because we haven’t created and assigned a click listener for it. Let’s do it similarly as with OK button. To begin with, create a listener:

    OnClickListener oclBtnCancel = new OnClickListener() {
       @Override
       public void onClick(View v) {
         // Change text of TextView (tvOut)
         tvOut.setText("Button Cancel clicked");
       }
     };

Then set it to the button:

btnCancel.setOnClickListener(oclBtnCancel);


Save, run and check the result. Both buttons now can process clicks.

Let’s talk once again about event processing mechanism by button click example. A button cannot process clicks on its own, it needs a listener for this, which is assigned using setOnClickListener method. When a button is clicked, listener reacts and runs the code from onClick method. It can be displayed like this:

 

It means that to implement this you have to follow these steps:

- create a listener
- implement onClick method
- assign listener to a button

And now the event processing system is ready.

 

In the next lesson we will:

- learn how to use one listener for several View-elements
- teach Activity to act as a listener


Присоединяйтесь к нам в Telegram:

- в канале StartAndroid публикуются ссылки на новые статьи с сайта startandroid.ru и интересные материалы с хабра, medium.com и т.п.

- в чатах решаем возникающие вопросы и проблемы по различным темам: Android, Compose, Kotlin, RxJava, Dagger, Тестирование, Performance 

- ну и если просто хочется поговорить с коллегами по разработке, то есть чат Флудильня




Language