Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

non-final variable inside an inner class

Tags:

java

android

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?

like image 898
Nick Robertson Avatar asked Dec 01 '22 04:12

Nick Robertson


1 Answers

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;
    }
});
like image 120
Emanuel Moecklin Avatar answered Dec 02 '22 16:12

Emanuel Moecklin