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 like:
OnClickListener clicks=new OnClickListener() {
@Override
public void onClick(View v) {
switch(v.getId())
{
case 1000: System.out.println("FIRST");
break;
case 1004: System.out.println("FOURTH");
break;
}
}
};
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));
btn.setOnClickListener(clicks);
if (row[pos].getChildCount() == 3) pos++;
ima++;
}
You can do this:
OnClickListener listener = 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;
}
}
};
for (int toShow = 1; toShow <= nShips; toShow++) {
btn = new Button(this);
// Set the click listener to all your buttons
btn.setOnClickListener(listener);
btn.setBackgroundResource(shipDrawable.get(ima));
btn.setLayoutParams(params);
row[pos].addView(btn);
btn.setId(shipId.get(ima));
if (row[pos].getChildCount() == 3) pos++;
ima++;
}
Cheers,
Yuvi
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With