0

My question is purely general. Why does Java force you to write complicated handlers that need to be attached to objects for a simple thing like a click?

So, why do I need to write:

public class ClickMe implements OnClickListener {

    void someMethod() {
        Button button = (Button) findViewById(R.id.button1);
        button.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        ....
    }
}

instead of something like

class myButton extends Button {
@override void onClick() {
// do something special
}

and then use that button on my layout?

I'm sure there are good reasons for this design, I just can't think of them!

Alexis C.
  • 91,686
  • 21
  • 171
  • 177
jackthehipster
  • 978
  • 8
  • 26
  • Because in general, one would wish to keep the how-to-be-a-button logic and the how-to-respond-to-events logic separate. – Oliver Charlesworth Feb 01 '14 at 13:49
  • @oli: your answer sounds reasonable. But it is always said use inheritance if a thing is-a super-thing. myButton is-a Button, so this applies. – jackthehipster Feb 01 '14 at 15:23
  • @commonsware: you may be right, I would have never though about searching for "composition". However I don't quite understand why my example is a composition? Isn't that when I use a class member instead of a subclass? The whole event-handler-design seems to me to be not composition (as it is used in the link you provided), but something else. But I may be wrong. – jackthehipster Feb 01 '14 at 15:26
  • 1
    "But I may be wrong" -- the widget holds a click listener. That is composition. Just because somebody else wrote the composition code does not make it somehow not be composition. "myButton is-a Button" -- that is a tautology. You decided to make a subclass, therefore it is a subclass. I cannot think of any popular widget-based UI frameworks that depended upon developers subclassing all of the widgets to make effective use of them. You subclass when you want to significantly change the behavior of the widget (e.g., how it renders), not merely for handling expected events. – CommonsWare Feb 01 '14 at 15:36
  • @commonsware: I wasn't sure about the terminology. The other discussions about compositions seem to have used it in the sense "use an aditional a class member instead of a subclass". Didn't know that the term is also used in this case. In that case, my question surely is a duplicate of those others. – jackthehipster Feb 01 '14 at 17:12

1 Answers1

1

I'm a bit confused on what you mean, but attaching onClickListeners to buttons is rather easy.

myButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
           //Do stuff when clicked 
        }
    });

Or you can implement View.OnClickListener in your activity or fragment, and set the onClickListener to be this.

gatlingxyz
  • 781
  • 6
  • 12