Reputation: 63
I have the following design :
<LinearLayout>
<ScrollLayout>
<LinearLayout> .... </LinearLayout> ----> TextView and ImageView dynamically created in this LinearLayout
</ScrollLayout>
</LinearLayout>
I need to detect touch events on the dynamically created ImageView(s)
. I don't know how many ImageView
will be created dynamically. How can I detect which ImageView
was touched by the user ?
Thanks for your help.
Upvotes: 0
Views: 1300
Reputation: 3847
You'll want to create one [maybe more] View.OnClickListeners in your java code. Then when each ImageView is added, you can assign that OnClickListener to it using View.setOnClickListener. To determine which was clicked, you can set a "Tag" using View.setTag() and then when onClick is called, use View.getTag() to determine which was clicked. The tag should be uniquely identifiable.
Here's some rough code (untested):
private OnClickListener imageViewListener extends View.OnClickListener{
public void onClick(View v){
Intent i = new Intent(v.getContext(), NewActivity.class);
i.putExtra("ImageURI", v.getTag().toString());
startActivity(i);
}
}
Then as you add images, you just set the tag and listener:
for(String uri: someList){
ImageView iv = new ImageView(this);
iv.setTag(uri);
iv.setImageUri(uri);
iv.setOnClickListener(imageViewListener);
}
Upvotes: 2
Reputation: 2614
You should use View.OnTouchLisetener class. So, after initializing your ImageView, add this call to it:
imageView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent e) {
//Your code here
}
});
Upvotes: 1