Dipak Keshariya
Dipak Keshariya

Reputation: 22291

How to Set onClicklistener Method of ImageView in Android?

I am Adding an array of ImageViews and set an image to each ImageView dynamically and I'm done with it. But the problem is how to set/define onClicklistener Method on an ImageView?

Here is my Code:

ImageView[] mImages;
int[] images = {R.drawable.sandle_icon1, R.drawable.sandle_icon2,
            R.drawable.sandle_icon3, R.drawable.sandle_icon4};

LinearLayout ll = new LinearLayout(this);
mScrollViewImage.removeAllViews();
ll.setOrientation(LinearLayout.VERTICAL);
mImages = new ImageView[images.length];
mScrollViewImage.addView(ll);
for (floop = 0; floop < sandleicon.length; floop++) {
    mImages[floop] = new ImageView(this);
    mImages[floop].setImageResource(images[floop]);
    ll.addView(mImages[floop]);
}

Any help will be greatly appreciated.

Upvotes: 13

Views: 65280

Answers (3)

Yashwanth Kumar
Yashwanth Kumar

Reputation: 29121

mImages[floop].setOnClickListener(clickListener);
private OnClickListener clickListener = new OnClickListener() {
    public void onClick(View v) { }
};

This is how you set onclicklistener to any view.

Upvotes: 3

Vinod Joshi
Vinod Joshi

Reputation: 7852

This worked for me in fragment

// update the Youtube thumbnail images
this.youtube_thumbnail = (ImageView) listView.findViewById(R.id.youtube_thumbnail);

this.youtube_thumbnail.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
    System.out.println("Adding youtube thumbnail");
}

Upvotes: 4

Rasel
Rasel

Reputation: 15477

for (floop = 0; floop < sandleicon.length; floop++) {
    mImages[floop] = new ImageView(this);
    mImages[floop].setImageResource(images[floop]);
    mImages[floop].setId(floop);
    ll.addView(mImages[floop]);
    mImages[floop].setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            //v.getId() will give you the image id
        }
    });
}

Upvotes: 25

Related Questions