I'm trying to create a generic page that creates image buttons with URL attached to them so they redirect you to a webpage on click. The number of the buttons is also generated on compile, as well as the links, they are retrieved from an online source.
My problem is, when I try to create an OnClickListener in a generic loop, they are not created until the button is clicked, therefore not until the end of the loop.
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(rowResourceId, parent, false);
ImageButton imageButton = (ImageButton) rowView.findViewById(R.id.imageButton);
int id = Integer.parseInt(Ids[position]);
String imageFile = MainActivity.GetbyId(id, MainActivity.getSaleArray()).imageURL;
String link=MainActivity.GetbyId(id, MainActivity.getSaleArray()).link;
imageButton.setTag(link);
imageButton.setOnClickListener(new ImageButton.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse((String) imageButton.getTag()));
context.startActivity(intent);
}
});
In the code above, I have an array of unknown size with ids and links, I have the data I require in each button's Tag but I cannot call them with imageButton.getTag() in OnClick block, it requires the variables to be 'final'. Can you help me find a way around this?
The rest of the code works perfectly, except the line intent.setData(...)
You can declare link
to be final and directly use it inside the OnClickListener
.
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(rowResourceId, parent, false);
ImageButton imageButton = (ImageButton) rowView.findViewById(R.id.imageButton);
int id = Integer.parseInt(Ids[position]);
String imageFile = MainActivity.GetbyId(id, MainActivity.getSaleArray()).imageURL;
final String link = MainActivity.GetbyId(id, MainActivity.getSaleArray()).link;
imageButton.setOnClickListener(new ImageButton.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(link));
context.startActivity(intent);
}
});