A listener (or observer) is an abstract class or interface that is used to provide functionality for an interactable UI component (e.g., a button). It is a part of the observer design pattern that detects any events related to the UI; for example, clicking or tapping a part of the screen executes a certain action. Every listener has a function (callback method) that is overridden when implementing a concrete listener.
A UI component is known as a view in Android.
onClick(View v)
In Android, the OnClickListener() interface has an onClick(View v)
method that is called when the view (component) is clicked. The code for a component’s functionality is written inside this method, and the listener is set using the setOnClickListener()
method.
Since the functionality of a component is usually different from other components, a listener (in Java) is commonly implemented using an anonymous class. Declaring a separate listener for each component also works, but it is not a good practice.
// Get button using its ID:Button btn = findViewById(R.id.my_btn);// Set OnCLickListener() using anonymous class:btn.setOnClickListener(new View.OnClickListener(){@Overridepublic void onClick(View v){// Functionality for the button...}});
Free Resources