Event Listeners Day

I first stumbled upon this piece of code from the BluetoothChat sample:

mSendButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                // Send a message using content of the edit text widget
                TextView view = (TextView) findViewById(R.id.edit_text_out);
                String message = view.getText().toString();

Because I haven't used any of the UI elements provided by Android, I had totally overlooked this way of setting up event listeners in Java. I hadn't even realised this was possible!

In other words, what it does is defining an instance of an anonymous class which implements the View.OnClickListener interface. OK, I know it sounds a bit complicated, so take your time before deciding whether you like it or not :-D

It's a tad more verbose than Javascript/ActionScript, but it might be useful in certain cases. As it says on the explanation for anonymous classes:

[...] anonymous classes are commonly used to subclass simple classes that do not take any constructor arguments [...]

Unfortunately, I suspect this only allows for setting one event listener per object and event type, in contrast to ECMAScript-based languages where we can add several listeners for the same object and event type. So this might not be entirely useful for you. But it's good to know...

Later, I was watching this video from Google I/O when Pavel (the speaker at the tech talk) mentioned a functionality in Chrome's Developer Tools which I had also ignored until now: the Event Listeners sub-panel --probably because they are always at the bottom of the view, well below the long list of Computed Styles, Styles, and so on :D

Event Listeners is the last option in the Elements panel, and if you dare unfolding it, it will show any associated event listeners for the currently inspected element. In capturing and bubbling order! Very cool! It's around minute 11 if you want to check it out by yourself, or here is an image:

Event listeners (blatantly taken from this tutorial)

Actually, the entire tech talk is littered with little tricks and shortcuts and revealing insights to turn you into a Developer Tools superuser, so I highly recommend watching it too. Do it:

It's amazing how blind we can be to something we literally see every day. Maybe that's part of the reason we routinely ignore those things?