我有一个活动,其中有10个完全相同imageButton
的资源都来自同一资源,myimage.png
我正在尝试使用设置onClick
10个按钮的每个按钮的监听器setTag()
。但是,所有这些imageButton
都绑定到同一听众。
这是我的代码:
public class AllButtonsActivity extends Activity {
ImageButton imageButton;
ImageButton allImageButtons[] = new ImageButton[10];
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ll);
createButtonsAndAddListener();
}
public void createButtonsAndAddListener() {
LinearLayout parent = (LinearLayout) findViewById(R.id.ll);
for (int i = 0; i < 10; i++) {
imageButton = new ImageButton(this);
imageButton.setImageResource(R.drawable.myimage);
imageButton.setTag(i);
allImageButtons[i] = imageButton;
allImageButtons[i].setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
int i = (Integer) imageButton.getTag();
Toast.makeText(AllButtonsActivity.this,
"ImageButton"+i+ "is clicked!", Toast.LENGTH_SHORT)
.show();
}
});
parent.addView(imageButton);
}
}
}
我想要的是,当单击第i个按钮时,吐司会弹出一条消息:
“ ImageButton” + i +“被单击!”
您的图片按钮变量在循环的每次迭代中都会被覆盖。而不是使用在活动开始时声明的变量,而是每次创建一个新变量
public void createButtonsAndAddListener() {
LinearLayout parent = (LinearLayout) findViewById(R.id.ll);
for (int i = 0; i < 10; i++) {
ImageButton imageButton = new ImageButton(this);
imageButton.setImageResource(R.drawable.mybutton);
imageButton.setTag(i);
allImageButtons[i] = imageButton;
allImageButtons[i].setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
int i = (Integer) imageButton.getTag();
Toast.makeText(AllButtonsActivity.this,
"ImageButton"+i+ "is clicked!", Toast.LENGTH_SHORT)
.show();
}
});
parent.addView(imageButton);
}
}
将您的代码更改为上面的代码,并ImageButton imageButton;
从活动变量声明中删除
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句