i need help in my idea. I need to create default OnClickListener for imageView, which do some code for all custom imageViews, and recive or do custom code for each imageView. For example: I have 10 imageViews tagged by different words, each imageview must be zoomed by click and play different songs. I do not want to use switch\case way, beacuse in this case i must repeat all "default" code 10 times.
Asked
Active
Viewed 69 times
0
-
you create the default method as public, and when you create each ImageView in the OnclickListener() method you invoke the default method... and viceverse.. can you please post what you've done so far... – geekCode Jul 08 '14 at 19:40
-
Look for [inheritance in Java](http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html). – m0skit0 Jul 08 '14 at 19:41
1 Answers
0
Extend ImageView
with your own class (for example MyImageView
) and implement OnClickListener
. For example
class MyImageView extends ImageView implements OnClickListener {
@Override
public void onClick(final View v) {
// Do your stuff
}
}
Of course you will need to use MyImageView
in your code instead of ImageView
. There's no way to add new methods to a class at runtime.
For more details on how this works, look for inheritance in Java.
-
so in Java i can't extend method in class for receiving code as a parametr/block? For e.g. ImageView1.setOnClickListener(defaultListener,{specCode}); – user3720146 Jul 10 '14 at 08:13
-
-
Yes you can, that's called an anonymous class, but in this case I highly doubt you want this, because this means you will have to write `{specCode}` the same in all classes, which is redundant. Avoid duplicating code is a better practice, and for this you can create a class that does this for you. If you don't want you don't need to extend `ImageView` and have this implementation in another class (for example `MyDefaultOnClickListener` class). – m0skit0 Jul 10 '14 at 14:08