我在 for 循环中以编程方式定义了一组图像按钮。对于每个按钮,我定义了它的 setOnClickListener 函数,它将一些数据放入 Intent 中,然后切换活动。但是,似乎无论我单击哪个按钮,检索到的额外数据都设置为 for 循环中的最后一个值。请参阅此处的代码:
public void onCreate(Bundle savedInstanceState) {
<...>
RelativeLayout rl = (RelativeLayout) findViewById(R.id.rlayout);
for (int i=1; i<=maxMapLoc; i++ ) {
mapLocation = i;
ImageButton btnMapLoc = new ImageButton(FirstActivity.this);
RelativeLayout.LayoutParams vp = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
btnMapLoc.setLayoutParams(vp);
btnMapLoc.setBackgroundColor(Color.TRANSPARENT);
btnMapLoc.requestLayout();
String imgName = "map_loc_" + mapLocation;
int id = getResources().getIdentifier(imgName,"drawable",getPackageName());
btnMapLoc.setImageResource(id);
int imgMapLoc = 2000 + mapLocation;
btnMapLoc.setId(imgMapLoc);
rl.addView(btnMapLoc, vp);
btnMapLoc.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("MapLocation", mapLocation);
startActivity(intent);
}
});
知道我做错了什么吗?
谢谢。