I create different buttons dynamically like this:
for (int toShow = 1; toShow <= nShips; toShow++)
{
btn = new Button(this);
btn.setBackgroundResource(shipDrawable.get(ima));
btn.setLayoutParams(params);
row[pos].addView(btn);
btn.setId(shipId.get(ima));
if (row[pos].getChildCount() == 3) pos++;
ima++;
}
I need to know the identity of each button because each other has different actions. Then, I try to set onClickListener like this:
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View btn) {
switch(btn.getId()){
case 1000: System.out.println("FIRST");
break;
case 1004: System.out.println("FOURTH");
break;
}
}
});
But it doesn’t work. It seems that the onClickListener only affects the last item was created. If I create four buttons, only the fourth will has an onClickListener.
How can I get my click listeners to work?
You can do this:
Cheers,
Yuvi