I would like to know if it is possible to create a listener to a listener. For example if I have a listener for a button, can I create a listener to that listener such that once the button is pressed the listener of the button listener would be notified.
My other concern is if I have a function call which has some listeners inside it would these listeners be destroyed on the return of the function call. For example can I have a function that I call in the beginning of the program that has listeners to listeners from my main program?
Of course you can. Listeners, or the “Observer Pattern”, are pretty straightforward. All the observer pattern really does is use interfaces to create a “contract” that lets everyone know that a certain class implements a certain method so that you can be confident that you can call it on that object.
So for example, you can create two interfaces like this:
The code that wishes to “trigger” these methods, must have a reference to those listeners. Typically this is done by exposing some public method to “set the listener(s)”. So in some class, you’d have
public void setOnClickListener() { this.onClickListener = listener; }The class that implements the listener can now call setListener(this). Note that “this” works here because interfaces in Java get you that kind of polymorphism. You can cast a class into any of its superclasses or interfaces that it implements. So in the class that wants to call “onClick” for example, all it cares about is that the class that contains the “onClick” IS an “onClickListener”. That’s all that class cares about. Now, as long as the class in which you implement the “onClick” has a reference to the SomeOtherListener (by previously being registered), then the onClick can callsomeOtherListener.onFoo();So, in short, (although it might be a poor design in some cases) you technically can have as many interrelated listeners as you want provided you set it up so that the relevant objects/classes have the references to those listeners that they need.
Sorry if this was a bit confusing. Also, its hard to provide a more detailed explanation without more details about what exactly you’d like to do.
EDIT
To the best of my knowledge, it is not possible to set up some “catchall” to log every GUI event in an Android app. Since interface methods are declared as empty methods that must be implemented, you’d have to specify, in your implementation, the precise logging that you’d like and go from there. You can certainly hack up the Android source to log something every time setOnClickListener is called, for example, but I can’t imagine that being super useful. Also, implicit in this is that you need to do this for every type of listener that’s available. Only listeners that you implement will be available for any sort of logging. If you don’t implement onTouch, for example, then there’s no logging to show for it…