How to use Button in an Android app?
Debashis Maharana, Aug 10/2019
Events are useful ways to collect data about user interaction with interactive components of the application like button press, text change, onTouch etc.
Button is a class in Android. Clicking of Button is an event which needs an event listener to listen and execute the appropriate code. An event listener is an interface of View class which contains callback methods.
We can use Button in 4 ways
Implementing the onClickListener interface on the Activity class and passing the self reference to the view.
In the .xml page, give value to “android:id” attribute to identify the Button:
In the .java file, retrieve the object of the button and set an onClickListener on the Button object. Pass the object of View.OnClickListener interface as parameter while registration of the listener with Button object. Override the onClick( ) method of View.OnClickListener interface and provide the code that is executed when button is pressed.
Create a variable with View.OnClickListener type by overriding onClick() method and providing the code to onClick( ) method that is executed when button is pressed.
Register the listener by calling setOnClickListener( ) method on the button object by passing reference of View.OnClickListener interface as parameter.
The .xml file remains same as before. The .java code is as follows:
Define the listener programmatically during the registration time. Override the onClick( ) method of View.OnClickListener interface and provide the code that is executed when button is pressed.
Setting the android:onClick property in .xml file