Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 helps will be greatly appreciated.

like image 269
Dipak Keshariya Avatar asked Sep 06 '11 09:09

Dipak Keshariya


People also ask

What is set OnClickListener?

In Android, the OnClickListener() interface has an onClick(View v) method that is called when the view (component) is clicked. The code for a component's functionality is written inside this method, and the listener is set using the setOnClickListener() method.

What is setOnClickListener new view OnClickListener ()?

setOnClickListener(this); means that you want to assign listener for your Button “on this instance” this instance represents OnClickListener and for this reason your class have to implement that interface. If you have more than one button click event, you can use switch case to identify which button is clicked.

How do I make a picture clickable on Kotlin?

We can add an image to the button simply by using attribute android:src in activity_main. xml file or by using setImageResource() method. In android, we can create ImageButton control in two ways either manually or programmatically.


2 Answers

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
        }
    });
}
like image 194
Rasel Avatar answered Oct 21 '22 23:10

Rasel


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");

            }
        });
like image 35
Vinod Joshi Avatar answered Oct 21 '22 22:10

Vinod Joshi