I am Adding an array of ImageView
s 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.
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.
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.
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.
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
}
});
}
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");
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With