I try to create dynamically a ImageView and I want to pass this imageView as a parameter to a method into the listener.
ImageView imageView1 = new ImageView(LookActivity.this);
imageView1.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
detectLocationAndShowPopUp(imageView1);
return true;
}
})
But I'm taking the following error:
Cannot refer to a non-final variable imageView1 inside an inner class defined in a different method.
I don't want to declare the imageView as final. How can I overcome this problem?
You can make a copy of imageView1 and then use the copy inside the listener:
ImageView imageView1 = new ImageView(LookActivity.this);
final ImageView imageView2 = imageView1;
imageView1.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
detectLocationAndShowPopUp(imageView2);
return true;
}
});
After Sam's comment I change my code to:
ImageView imageView1 = new ImageView(LookActivity.this);
imageView1.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {
detectLocationAndShowPopUp((ImageView) view);
return true;
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With