Brad
Brad

Reputation: 11515

How do you Override onClick in an Android ImageButton derived class

I've seen this asked a thousand times in a thousand different ways, but still can't get it to work...

I created a class which I've derived from ImageButton. I want to define my "on-click" behavior in the class.

I know I can do something inside my Activity's onCreate like:

myButton b;
b = (myButton)findViewById(R.drawable.mybutton);
b.setOnClickListener(new View.OnClickListener() {
     ...etc...

but I want to define the code where it should be, in the derived class.

I first thought I could define it as:

 @Override public void onClick(View v) {

...but I get an error saying that I can't use "@Override" here because "onClick" isn't in the superclass. (When trying to remove "@Override", it just builds and runs, but never gets called). I've also tried:

 @Override public void onClickListener(View v) {

...and several variants of "implements onClickListener" and "implements OnClickListener" to no avail.

This should be fairly simple - any ideas??

Upvotes: 1

Views: 3481

Answers (2)

Malcolm
Malcolm

Reputation: 41510

This is because there actually is no method onClick() in views. The work is done in the onUpKey() in the View class.

However, if you want to listen to clicking events in the subclass, this could be done very easily. You can either create an inner class which implements View.OnClickLister and use it to listen to events or even simpler, implement the interface in your class and set it as a listener during construction. The latter will look like this:

class YourClass extends ImageButton implements View.OnClickListener {
    public YourClass() {
        setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        //Your code
    }
}

LAS_VEGAS has already posted how the first variant with the inner class may look like.

Upvotes: 1

Caner
Caner

Reputation: 59258

   b.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
          derivedClassFunction(v);
      }
  });

   public void derivedClassFunction(View v) {
          /* code...*/
   }

Another way:

public class DerivedClass extends ImageButton implements View.OnClickListener {
    /*code...*/
    b.setOnClickListener(this);
    /*code...*/
    @Override
    public void onClick(View v) {
        /*code...*/
    }

}

Upvotes: 1

Related Questions