You can declare a final
local variable inside the loop:
for(int i = 0; i < level.myItems.size(); i++){
final int j = i;
itemsInInventory[i].setButtonListener(new UIButtonListener(){
public void pressed(UIButton button, Sprites sprite){
itemsInInventory[j].performAction();
}
});
}
Or, better, since you just need the button, not i
:
for(int i = 0; i < level.myItems.size(); i++){
final UIButton btn = itemsInInventory[i];
btn.setButtonListener(new UIButtonListener(){
public void pressed(UIButton button, Sprites sprite){
btn.performAction();
}
});
}
Or even better (since presumably the first argument to pressed
is the button itself):
for(int i = 0; i < level.myItems.size(); i++){
itemsInInventory[i].setButtonListener(new UIButtonListener(){
public void pressed(UIButton button, Sprites sprite){
button.performAction();
}
});
}
Note that with the last version, you don't need a separate UIButtonListener
for each button. Just set them all to have the same listener and the listener will dispatch to the appropriate button automatically:
UIButtonListener listener = new UIButtonListener(){
public void pressed(UIButton button, Sprites sprite){
button.performAction();
}
};
for(int i = 0; i < level.myItems.size(); i++){
itemsInInventory[i].setButtonListener(listener);
}