Hello readers, welcome to the fourth post of my Android Application Development Tutorial from Scratch. Today we will see Android OnClickListener. In the last post of Android Application Development Tutorial we created a Button and EditText. In this post we will add functionality to the button using Android OnClickListener. So lets begin.
A Quick Recap of the Last Post
- In the last tutorial we created an Android Studio project named HandlingButton.
- We created the following layout
- So if you haven’t gone through the last post, first go through the last post. Now lets move ahead to some coding part.
Moving on to Java Coding
- Open MainActivity.javaÂ
- After opening MainActivity.java you will see the following code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
package net.simplifiedcoding.handlingbutton; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } } |
- Now don’t worry if it is bouncing over your head :P. We will understand every line. Everytime you will create a project the above given snippet would generate automatically.
- So in the above code we have a class MainActivity. Inside the class we have three overriden methods. Leave the first method and delete the remaining two methods (onCreateOptionMenu and onOptionsItemSelected). After deleting the methods you will have the following code.
1 2 3 4 5 6 7 8 9 10 11 |
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } } |
Understanding the Above Code
- MainActivity: It is the name of the class we are having. It is also named as your activity name. If you remember the project creation we have given this name.
- AppCompatActivity: Our class MainActivity is extending this class.  You can see the complete reference of AppCompatActivity from the official website.
- onCreate(Bundle savedInstanceState): This is an overridden method.  It is inside the AppCompatActivity class. This method will be executed when the app is opened (the activity is created). So basically you can think that it is the main method. We will learn the details about this in further posts when we will learn the Activity Life Cycle.
- Bundle: It is another predefined class. It is basically used for passing data between android activities.
- setContentView(R.layout.activity_main): This method takes a layout and it set the view as the layout to the activity.  We created a layout named activity_main.xml. As I told you before that all the ids for all the components are generated automatically and stored inside R.java file. And that is what we are doing here. We are selecting the id of our layout from R.java file (R.layout.activity_main).
The above mentions things are generated automatically. Now we need to code our things. So the layout we created is having a Button and an EditText. We have predefined classes in android for all the compnents. So now come inside the MainActivity class.
- We will declare two instances one for Button and one for EditText.
1 2 3 4 5 |
public class MainActivity extends AppCompatActivity { private Button button; private EditText editText; |
- Now if you are getting error as shown in the below image
- This error is caused because you haven’t imported the packages. So just put the cursor in the word causing error. In my case it is EditText.
- Press alt+enter
- Click on import class. And you’ll see your error has gone away. Bingo!
- Now we have the instances for our Button and EditText
- Now we will initialize our instances inside the onCreate method.
Initializing a View
- All these components Button and EditText are called View. We have also a predefined class named View in android. For initializing a View from XML layout file, we have a method findViewById().Â
findViewById(int id)
- It takes a parameter id. As I told you that every components has an specific id that is stored in R.java file. So we will provide the id from the R file. We don’t need to go to the R file actually it is the id we have given while creating the component. And with the name of the id a variable is created inside the R file with a unique hex value. So lets initialize our components.
- Come inside onCreate() method and write the following code
- If you are also getting the error then don’t worry. We are getting the error because the method findViewById() returns a View. But in left side we are having a Button. So the error is because of the type mismatch. Put the cursor in the line and press alt+enter
- Click on Cast to android.widget.Button
- So now the error has gone. So everytime we need to cast to the respective view if we are using findViewById() method.
- So now our onCreate() method would be
1 2 3 4 5 6 7 8 9 10 |
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button) findViewById(R.id.button); editText = (EditText) findViewById(R.id.editText); } |
- So we have initialized our button and editText. So what I will be doing from here is I will get an given name from the editText and will show a greeting message in the same editText.
- So for this I will create a separate method. So create a method named showMessage().Â
1 2 3 4 5 |
private void showMessage(){ } |
- Now for manipulating our editText we will use the method getText() and setText()
Handling EditText
- getText(): This method returns an Editable instance. And it contains the text from the EditText. So for storing the Text into a String object, we can use the toString() method to convert it into String.
- setText(String s):This method takes a string and set the string to EditText.
- So using the above methods we can code our method showMessage().
1 2 3 4 5 6 7 |
private void showMessage(){ String s = editText.getText().toString(); String greeting = "Hello "+s; editText.setText(greeting); } |
- Now this method should execute when the user will tap on the button.
Using Android OnClickListener Interface
- We have an Interface OnClickListener inside the View class. This interface can be used for handling the button. So first implement this interface into your MainActivity class.
- We are getting an error this is because we have implemented the interface OnClickListener but we did not override the methods inside the interface OnClickListener.
- Now put the cursor on the line and press alt+enter
- Click on Implement methods
- Now select onClick() and click OK.
- Now you will see the following method in your MainActivity class.
1 2 3 4 5 6 |
@Override public void onClick(View v) { } |
- This method will be executed on button tap but before we have to specify the listener for our button. We can do this using setOnClickListener() method
setOnClickListener(View.OnClickListener l)
- This method takes the reference to the Listener and registers a callback to be invoked when the View is clicked.
- So we have the listener in the same class MainActivity. So we can pass the reference using this. So write the following code inside onCreate().
- Now after doing this our overriden method onClick() will execute when the button is tapped. So now we can call our method showMessage() inside onClick()
1 2 3 4 5 6 |
@Override public void onClick(View v) { showMessage(); } |
- So the final code we are having is
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
public class MainActivity extends AppCompatActivity implements View.OnClickListener { private Button button; private EditText editText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button) findViewById(R.id.button); editText = (EditText) findViewById(R.id.editText); button.setOnClickListener(this); } private void showMessage(){ String s = editText.getText().toString(); String greeting = "Hello "+s; editText.setText(greeting); } @Override public void onClick(View v) { showMessage(); } } |
- Now run your application
- Enter your name in the EditText and Tap on the Button. You will see the greeting message in EditText. So I wrapping up this Android OnClickListener tutorial here. In the next tutorial we will see some more methods to Handle our button.
Next Post:Â Android OnClickListener Contd…
Prev Post:Â Button and EditText