我想以编程方式创建多个ImageButtons。我可以创建它们但是click事件监听器不断接收相同的视图(按钮2),无论我是否单击按钮0,按钮1或按钮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);
}'
点击事件监听器:
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());
}
};
对于任何绘制的图像按钮,当我点击时我得到:点击绿球 - &gt; 2 v.ID-&gt; 2
按钮位于不同的位置(我为每个按钮设置了不同的填充,但为了简化代码,我没有把它放在这里)
答案 0 :(得分:10)
尝试添加onClickListener
-
private View.OnClickListener ClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
int selected_item = (Integer) v.getTag();
}
};
修改强>
尝试创建 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]);
}
答案 1 :(得分:0)
这是因为你没有在同一个地方设置按钮,所有按钮的布局。
Use Aboveof,Belowof,left,right,center
params.addRule(RelativeLayout.ALIGN_PARENT_ABOVE);
relativeLayout.addView(button, params);
答案 2 :(得分:0)
试试这段代码:
RelativeLayout gameBoard = (RelativeLayout)findViewById(R.id.RelGameboard);
ImageButton[] imageButtons;
private final int NUMBER_OF_IMAGE_BUTTONS = 5; //your number of image buttons
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.CENTER_IN_PARENT,1);
imageButtons = new ImageButton[NUMBER_OF_IMAGE_BUTTONS];
for(int i = 0 ; i < NUMBER_OF_IMAGE_BUTTONS; i++){
imageButtons[i] = new ImageButton(this);
imageButtons[i].setImageResource(R.drawable.bola_verde);
imageButtons[i].setLayoutParams(lp);
imageButtons[i].setOnClickListener(mGreenBallOnClickListener);
imageButtons[i].setBackgroundColor(Color.TRANSPARENT);
imageButtons[i].setTag(i);
imageButtons[i].setId(i);
gameBoard.addView(imageButtons[i]);
}