Android Button Click Tutorial (In Detail)

In this tutorial we will learn how to perform an action when a button is clicked. Here, we will display a Toast notification containing a sample text when the button is clicked.

Let’s look into our layout file “activity_main.xml”.

activity_main xml

We will take a thorough tour of the button code. For the timing, we will ignore the code from line 1 to line 11 and line 19. We will just focus on the code from line 13 to 17. That is the code which displays the button on the device screen.

Line 13: This line is the starting of the Button code.

Line 14: This is the line which sets the width of the button. “match_parent” means the button will cover the total width of its parent view. Here, the parent view is the RelativeLayout starting in Line2.

Line 15: This line sets the height of the button. “wrap_content” means the button will occupy only the height that is required to accommodate the text in it. This applies to the android:layout_width property also.

Line 16: This line writes the text on the button.

Line 17: This line assigns an unique id to the button. The id of each element in the xml file should be unique, else there will be an error. “/>” ends the code of the button.

Now let’s look into the MainActivity.java file.

main activity

Line 11: We declare the button variable.

Line 18: Here, we initialize the variable. The “findViewById(R.id.button)” searches the xml file for the UI element with “button” as id and returns a View object. But, we cannot assign the view object to the variable of Button class. So, we cast the View object returned by “findViewById(R.id.button)” to Button class by using (Button).

Line 19-25: In these lines, we assign a on click listener interface to the button, so that, the button responds to our click. In line 22 and 23, we display a Toast notification. The Toast class has a static method called “makeText()”, which takes three argument. First, a context object, second, a String object and Third, an integer. “MainActivity.this” is our context object. Our String object should be the String which we want to display when the Button is clicked. “Toast.LENGTH_SHORT” is a static integer constant. In order to show the Toast notification, we need to call the show() method.

Now, we get this as output, when the button is clicked.

toast

Hope you enjoyed this tutorial. Thank You.

Note: In JAVA and ANDROID, most of the code is self-explanatory i.e. you can guess the use of a class or object or method from its name. For example, “setOnClickListener(…)”  sets a click responder.

Be the first to comment

Leave a Reply

Your email address will not be published.


*