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;
}
}
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
}
});
@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
Subscribe with your email to receive News updates