Reputation: 1765
I have a loop that runs through an array of image views, adding an event listener to each, how can I find out which image view was pressed inside the listener?
imageViewArray[i].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
}
});
Upvotes: 1
Views: 466
Reputation: 56697
Doesn't the v
parameter to the onClick
method provide a reference to the ImageView
?
EDIT
The thing is: You are not adding the same listener to all of the ImageView
s in your code - every ImageView
in your array gets its own listener.
In the listener's onClick
method, the View
that raised the event is passed in v
, so when working with v
you're working with the clicked ImageView
.
To find the index of the ImageView
in your array, you might as well set the ID as suggested by others and then use v.getId()
, or you could loop over your array and check whether imageViewArray[i] == v
, in which case i
is the index of your ImageView
within the array.
Upvotes: 1
Reputation: 40193
imageView.getId()
will return you the ID you give this ImageView
in findViewById()
method. Then you can check the ID's in a switch block. Hope this helps.
Upvotes: 0