I want to create several ImageButtons programmatically. I am able to create them but the click event listener keeps receiving the same view (Button 2), whether I click on button 0 ,button1 or button 2.
RelativeLayout gameBoard = (RelativeLayout) findViewById(R.id.RelGameboard);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.CENTER_IN_PARENT,1);
for(int i = 0 ; i < 3 ; i++)
{
ImageButton btnGreen = new ImageButton(this);
btnGreen.setImageResource(R.drawable.bola_verde);
btnGreen.setLayoutParams(lp);
btnGreen.setOnClickListener(mGreenBallOnClickListener);
btnGreen.setBackgroundColor(Color.TRANSPARENT);
btnGreen.setTag(i);
btnGreen.setId(i);
gameBoard.addView(btnGreen);
}'
Click event listener:
private View.OnClickListener mGreenBallOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
//check which green ball was clicked
ImageButton imgBtn = (ImageButton) v;
Log.i("greeny","Clicked on green ball->"+imgBtn.getTag()+" v.ID->"+v.getId());
}
};
For any imagebutton drawn, when I click I get : Clicked on green ball->2 v.ID->2
The buttons are in different positions ( i set a different padding for each one of them but in order to simplify the code I didn't put it here )
We can add an image to the button simply by using attribute android:src in activity_main. xml file or by using setImageResource() method. In android, we can create ImageButton control in two ways either manually or programmatically.
There's no differences, except default style.
Try adding a onClickListener
-
private View.OnClickListener ClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
int selected_item = (Integer) v.getTag();
}
};
EDIT
Try creating a array of ImageButtons
-
ImageButton[] btnGreen = new ImageButton[3];
for (int i = 0; i < 3; i++) {
btnGreen[i] = new ImageButton(this);
btnGreen[i].setImageResource(R.drawable.bola_verde);
btnGreen[i].setLayoutParams(lp);
btnGreen[i].setOnClickListener(ClickListener);
btnGreen[i].setBackgroundColor(Color.TRANSPARENT);
btnGreen[i].setTag(i);
btnGreen[i].setId(i);
gameBoard.addView(btnGreen[i]);
}
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