Events or Listners

An Event Listener is an interface in the View class that contains a single callback method. These methods will be called by the Android framework when the View to which the listener has been registered is triggered by user interaction with the item in the UI.

Like button presses or screen touch etc. The Android framework maintains an event queue as first-in, first-out (FIFO) basis. You can capture these events in your program and take appropriate action as per requirements.

Let's understand this by creating an example, we will discuss button event listener, first of all we have to register event listener to button object as below:

AppCompatButton btn = findViewById(R.id.btnOk);
btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
                
    }
});

In above code snippet, AppCompatButton has a method i.e. setOnClickListener() to registered event listener, and each class has separate methods to registered event listener.

Event Listeners

Event Listener Description
setOnClickListener() This is called when the user either clicks or touches or focuses upon any widget like button, text, image etc
setOnLongClickListener() This is called when the user either clicks or touches or focuses upon any widget like button, text, image etc. for one or more seconds.
setOnFocusChangeListener() This is called when the widget looses its focus ie. user goes away from the view item
setOnTouchListener() This is called when the user presses the key, releases the key, or any movement gesture on the screen.
setOnMenuItemClickListener() This is called when the user selects a menu item.
onCreateContextMenuItemListener() This is called when the context menu is being built(as the result of a sustained "long click)

Now we will show you how to add setOnTouchListener() on AppCompatButton object as below:

AppCompatButton btn = findViewById(R.id.btnOk);
btn.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        switch (motionEvent.getAction()) {
            case MotionEvent.ACTION_DOWN:
                Toast.makeText(MainActivity.this, "Touch is down", Toast.LENGTH_SHORT).show();
                break;
            case MotionEvent.ACTION_UP:
                Toast.makeText(MainActivity.this, "Touch is relased", Toast.LENGTH_SHORT).show();
                break;
        }
        return false;
    }
})