I have programatically defined a set of imagebuttons in a for loop. For each button, I defined its setOnClickListener function which will put some data in the intent and then switch activity. However, it seems like no matter which button I clicked on, the extra data retrieved is set the the last value int he for loop. See code here:
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);
}
});
Any idea what I did wrong?
Thanks.
You could add a tag to your button with the current mapLocation value.
The reason why you only get the last value of
mapLocationis that the code inside your onClick() is run when the user pushes a button. In other words your are queryingmapLocationlong after the loop built your buttons. You need to create a reference to the currentmapLocationin each loop iteration, like with the tag feature.