我想以编程方式创建几个 ImageButtons。我能够创建它们,但单击事件侦听器始终接收相同的视图(按钮 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());
}
};
对于绘制的任何图像按钮,当我单击时,我得到:单击绿色球-> 2 v.ID-> 2
按钮位于不同的位置(我为每个按钮设置了不同的填充,但为了简化代码我没有把它放在这里)