Since we don’t know much about why you want to do this, it’s hard to do what is best. If you want the original listener to remain intact / untouched, you can use a decorator / wrapper template.
Wikipedia Drawing Decorator
In the specific case, this means that it is quite comparable to your Runnable approach, but you are not dependent on another interface. Everthing is handled through View.OnClickListener , which has the following advantages:
- This is a general approach by which you can even “expand” listeners that you don’t have access to the source or that you don’t want to change.
- You can create extension behavior at runtime, and you can extend already created instances (as opposed to using inheritance)
Extensions do not need to know that they are extensions, they are just normal OnClickListeners . In your approach, Runnable extensions are "special" and, for example, they do not receive the View parameter of the onClick method.
public class OriginalOnClickListener implements View.OnClickListener{ @Override public void onClick(View v) { Toast.makeText(MainActivity.this,"Original Click Listener",Toast.LENGTH_LONG).show(); } } public class ExtensionOnClickListener implements View.OnClickListener{ @Override public void onClick(View v) { Toast.makeText(MainActivity.this,"Extension Click Listener",Toast.LENGTH_LONG).show(); } } public class DecoratorOnClickListener implements View.OnClickListener { private final List<View.OnClickListener> listeners = new ArrayList<>(); public void add(View.OnClickListener l) { listeners.add(l); } @Override public void onClick(View v) { for(View.OnClickListener l : listeners){ l.onClick(v); } } }
And this is something like this:
DecoratorOnClickListener dl = new DecoratorOnClickListener(); dl.add(new OriginalOnClickListener()); dl.add(new ExtensionOnClickListener()); editText.setOnClickListener(dl);
source share