Android Button Example

In this tutorial you will get android button example.

Button is a very basic and commonly used UI widget of Android. It can be pressed or clicked and we can perform some action on its click event.

We can define a button in XML layout by using <Button> tag. In this tutorial I have given an example in which if the user presses the button then a message is displayed in Toast.

We can handle the click event on button in two ways.

  1. Using OnClickListener
  2. Using android:onClick

 

Android Button Example

OnClickListener

We can handle button click event by using OnClickListener in following way.

Create a new project with package name thecrazyprogrammer.androidexample and add following code in respective files.

activity_main.xml

 

MainActivity.java

 

Screenshot

Android Button Example

 

In case you use more than one button in Activity then you have to apply OnClickListener separately on each button as shown below.

 

android:onClick

We can also handle click event by assigning a method to button in XML layout by using android:onClick attribute. When button is clicked, the associated method is called. Make sure the method is public void and accept View as a parameter. See below example to learn how to implement this.

Create a new project with package name thecrazyprogrammer.androidexample and add following code in respective files.

activity_main.xml

 

MainActivity.java

 

In above example I have used method name as btnAction. You can give its name according to you. 

In case you use more than one button in Activity then click event for each button can be handled in following way.

 

Comment below if you have any queries related to above android button example.

1 thought on “Android Button Example”

Leave a Comment

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