views:

24

answers:

1

I have a custom class that I've written that extends ImageView (for Android Java). I want to add a ClickListener to every instance I create of the class that will do the same thing (just animate the ImageView.

I tried a few different things to no avail. The code below is what I want to accomplish but it's being applied to an instantiated object of the class.

MyCustomImageView fd = new MyCustomImageView(this);
fd.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                Animater(fd);
            }
        });

I tried using "implements onClickListener" on the class declaration and then a public void onClick() method in the class, and that didn't work for me.

I also tried using the code snippet above with a "this" instead of "fd" and that didn't work either.

I'm relatively new to java and this is out of the scope of my knowledge. Any assistance you can provide is greatly appreciated.

A: 

It's really easy. You have to do it in your custom class:

public class MyCustomImageView extends ImageView{

    public MyCustomImageView(Context context){
        super(context);
        setOnClickListener(theCommonListener);
    }

    private OnClickListener theCommonListener = new OnClickListener(){
        public void onClick(View v) {
             // do what you want here
        }
    }
}

There are other ways to do it, but this is one is really easy to implement and understand. Every instance of MyCustomImageView will have the same event listener (unless you override it from outside).

Cristian
hmm... I added that along with another method that I'm calling when the image is clicked, and it's never reaching the other method. Eclipse is also telling me that theCommonListener is never read locally...any ideas?
Kyle
oops my bad. I forgot to remove the listeners from the objects I created...this is perfect! thanks.
Kyle