How to use the loop iteration variable in the onclicklistener method of a button

advertisements

this is my code..

for (int i = 0; i < 12; i++)
   {
          buttons[i] = (Button)findViewById(R.id.buttonid);
        @Override
        public void onClick(View v) {
           // in this method I want to set the button text to the iteration variable 'i'
        }
    });
   }

my need is to get the iteration variable inside the onclick method. I tried by assigning the i value to another int variable(with and without using final) before the onclick method. But all this shows some errors.

Thanks in advance.


Make the i variable global by declaring it at the top of your class outside methods. private int i; http://en.wikipedia.org/wiki/Global_variable

Then you don't need to say int inside the for loop

for (i = 0; i < 12; i++)
   {
         buttons[i] = (Button)findViewById(R.id.buttonid);
        @Override
        public void onClick(View v) {
           // in this method I want to set the button text to the iteration variable 'i'
        }
    });
   }

You could also use the final modifier as mentioned in the comments, you would have to post how you tried to use it if you wanted us to debug your error.