Search code examples
androidbuttonimagebutton

ImageView Button Toggle in Android


I'm trying to make an ImageView button toggle when I click on it. I've got the below code:

    ImageView button01 = (ImageView) findViewById(R.id.button01);
    button01.setOnClickListener(new OnClickListener() {
        int button01pos = 0;
        public void onClick(View v) {
            if (button01pos == 0) {
                button01.setImageResource(R.drawable.image01);
                button01pos = 1;
            } else if (button01pos == 1) {
                button01.setImageResource(R.drawable.image02);
                button01pos = 0;
            }
        }
    });

But for some reason button01 is underlined in red in Eclipse and it gives the error:

Cannot refer to a non-final variable button01 inside an inner class defined in a different method

Does anyone know why it's doing this and how to fix it?

Thanks


Solution

  • Here is the working code:

    final ImageView button01 = (ImageView) findViewById(R.id.button01);
    button01.setOnClickListener(new OnClickListener() {
        int button01pos = 0;
        public void onClick(View v) {
            if (button01pos == 0) {
                button01.setImageResource(R.drawable.image01);
                button01pos = 1;
            } else if (button01pos == 1) {
                button01.setImageResource(R.drawable.image02);
                button01pos = 0;
            }
        }
    });