I created an ImageView
ImageView _view;
ViewGroup _root;
public void CreateImageView() {
_root = (ViewGroup) findViewById(R.id.root);
for (int i = 0; i < 5; i++) {
_view = new ImageView(this);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(100, 100);
layoutParams.leftMargin = 150;
layoutParams.topMargin = 50;
_view.setLayoutParams(layoutParams);
_view.setId(i);
_root.addView(_view);
}
}
when i click on the imageview which has the id = 3, a Toast should be called. How can I achieve this?
Take an Integer array of imageview like _view = new ImageView[size];
and within forloop
initialize and set tag to imageview and then while handling click event, get the tag likeint k = (Integer) v.getTag();
like this way you get the exact click of your view.
ImageView _view;
ViewGroup _root;
public void CreateImageView()
{
_root = (ViewGroup)findViewById(R.id.root);
_view = new ImageView[5];
for ( int i = 0; i< 5;i++)
{
_view[i] = new RadioButton(this);
_view[i].setTag(i);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(100, 100);
layoutParams.leftMargin = 150;
layoutParams.topMargin = 50;
_view.setLayoutParams(layoutParams);
_root.addView(_view[i]);
}
}
Click Event#
_view[j].setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub.
int k = (Integer) v.getTag();
if(k==3){
Toast.makeText(this, "Your Message", Toast.LENGTH_LONG).show();
}
}
}
when i click on imageview id = 3, a Toast.maketext will be call How can i do that?
Add something like this to your loop:
if(i == 3) {
_view.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getBaseContext(), "Message", Toast.LENGTH_LONG).show();
}
});
}
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