Reputation: 99
I'm trying to pass an ID to my new activity on creation.
The obvious solution seems to be to use "Intent.putExtra(name, value);". But as the intent is only created on click, all of my buttons have the same Intent extras (useally null).
Is there any way i can initialize these from a loop?
for ( int i = 0; i< IDList.size() ; i++)
{
//Get Information from ID
btnDetails.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent(getApplicationContext(),DetailActivity.class);
intent.putExtra("", IDList.get(i));
startActivity(intent);
}
});
//Add To Screen
}
In the code snippit IDList.get(i) is out of scope and a new Final Int isn't checked until the button is clicked, also going out of scope.
Is there any other was i can send the variable on click?
Upvotes: 4
Views: 1277
Reputation: 157487
You can a inner class that implements OnClickListener and takes as parameter the id. For instance
private class MyOnClickListener implements OnClickListener {
private final int mId;
public MyOnClickListener(int id) {
mId = id;
}
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), DetailActivity.class);
intent.putExtra("", mId);
startActivity(intent);
}
}
for ( int i = 0; i< IDList.size() ; i++) {
btnDetails.setOnClickListener(new MyOnClickListener(IDList.get(i)));
}
Upvotes: 4