Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to indentify a view in layout?

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?

like image 997
user1855435 Avatar asked Jan 15 '23 22:01

user1855435


2 Answers

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();
      }

    }
 }
like image 172
RobinHood Avatar answered Jan 22 '23 12:01

RobinHood


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();
        }
    });
}
like image 35
Sam Avatar answered Jan 22 '23 12:01

Sam