Android, event listener?
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.OnC开发者_如何学运维lickListener() {
public void onClick(View v) {
}
});
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.
set id for each on the index value like eg: image_view.setId(i);
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.
精彩评论