Genaut
Genaut

Reputation: 1862

Set Onclick on many views Android

I have a serie of ImageViews on my Activity. And I wanna execute a method when one of these is touched. I have the next:

  public void onClick(View v) {

          switch(v.getId()){

          case R.id.image1:
              mymethod(1,1,movimientos,(ImageView)v);
              break;
          case R.id.image2:
              ponerficha(1,2,movimientos,(ImageView)v);
              break;
          case R.id.image3:
...

But the method isn't executed, The problem not is the method, because any code in the cases not work. Any idea?

Upvotes: 1

Views: 229

Answers (3)

Simon Dorociak
Simon Dorociak

Reputation: 33515

First thing what you need to check if you already register onClickListener for your Images

image.setOnClickListener(this);

(This you have to use if your class implements OnClickListener interface)

Then how you declare and initialize your ImageViews, whether have own ids.

image = (ImageView) findViewById(R.id.someId)
anotherImage = (ImageView) findViewById(R.id.anotherId)
...

You can work with onClickListeners like with anonyme classes like

image.setOnClickListener(
   new View.OnClickListener() {
      public void onClick(View v) {
         // some actions
      }
});

but more complex and better in the case you have many widgets to set implement OnClickListener.

public class ClassName extends Activity implements View.OnClickListener {}

Upvotes: 1

BDFun
BDFun

Reputation: 551

You need to add an onClick handler to each view you are interested in processing clicks for.

How you do it depends on how you want to process the click events. You can either use hawaii.five-0's approach and have one event handler for everything, or you can have one event handler per view item which you could add in the onCreate method of your activity:

ImageView imageView = (ImageView) findViewById(R.id.image_view);
imageView.setOnClickListener(new OnClickListener() 
{
    @Override
    public void onClick(View v) 
    {
        // Do something
    }
}

Upvotes: 0

Zaid Daghestani
Zaid Daghestani

Reputation: 8615

First, your activity has to implement View.OnClickListener like so

public class myActivity implements View.OnClickListener {

Then you need to set your on click listener for your ImageViews. If all your ImageViews are in a linearlayout then the code would look like this

LinearLayout llImageViewHolder = (LinearLayout) findViewById(R.id.llImageViewHolder);
for (int i = 0; i < llImageViewHolder.getChildCount(); i++ {
    ImageView iv = (ImageView) llImageViewHolder.getChildAt(i);
    iv.setOnClickListener(this);
}

Cheers.

Upvotes: 0

Related Questions