Android Button Clicks Tutorial




Everyone must have at some point wondered how does a button click perform a specific thing in android . Button clicks are very important as they help to trigger some code.Whenever we need to send some data from one activity to another we use button clicks as well like for forms. We ask the user to fill in data and on button click we can validate the data and do some other task So today we will learn how to perform a button click and do some action based on the button click.


  • Start a new Android project and select empty activity

  • Using XML get an Edit text as well as a button on the activity


                     As you can see from the above image I have added "id" for button as well as the edittext. We need to reference these "id"s in our java file so that on that button click we can get the text from the text box and perform some action.

  • Go to java file and reference the button and add OnClickListener for the button. With this listener , whenever a user presses the button , the code inside the onclicklistener will get executed.
       From the image above , we can use findviewbyid option to reference the data from the xml file having the specific id. This is how I have referenced it inside the java file.

  • Now lets write the code inside the click listener of the button. I will get the data written in the edit text and then display a toast with the data inside. A toast is nothing but a small message which is displayed on any activity.

  • Lets run the app and see the result of the app


     As expected , on the click of a button a small toast is displayed on the app which shows the text inside the text box. In this way we can do multiple functionalities using a button. In the next tutorial , we will learn about starting a new activity and sending data from one activity to another using a button click.










                 
















Comments