Friday, October 30, 2020

Create a custom event listener in Java, Android Studio

We often face a problem that we need local/global variables accessible inside a listener class, let say OnClickListener, OnTouchListener. But, since the listener is an object of another class, even our global variables are not accessible inside its overriden methods such as onClick,onTouch etc. So, how to pass values into the listener methods?

We can implement our custom listener class that implements the default listener classes. The class should consists of all the variables/attributes and their variables can be passed using its constructor. Now, the variable values are accessible inside the listener methods since we set them local on creation. The variables may either be primitive or composite.

First, we need to add the class definition on the file itself where we need it or in a separate file. A sample custom event listener class will be like,
class CustomOnClickListener implements View.OnClickListener {
    int id;
    String name;
    
    public abstract boolean onTouch(View v, MotionEvent event);
    
    CustomOnClickListener(int id, String name){
        this.id = id;
        this.name = name;
    }
}

Since the class implement the default event listener, you can use the listener class within the appropriate set listener method, setOnClickListner, setOnTouchListner etc. You need to pass the arguments into the constructor when you instantiate objects of the custom listener.
myButton.setOnClickListener(new CustomOnClickListener(globalKey, globalName) {
                @Override
                public boolean onClick(View v, MotionEvent event) {
                    // your lister action code here
                    myButtonPressed(id, name);    //any  method in the main class
                }
            });

Thanks for reading. Please share if you find it useful !
Subscribe with your email to receive News updates
 

 

No comments:

Post a Comment

Whats New

How redundant uploads can be avoided in social media apps?

People spend more time on social media, and it influences the most and changes to societies. They want to share photos and videos often when...

You may also like to read

x

emailSubscribe to our mailing list to get the updates to your email inbox...

Delivered by FeedBurner