Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android which button index from array was pressed

How do I set up a OnClickListener to simply tell me which index button was pressed from an array of buttons. I can change text and color of these buttons using the array. I set them up like this.

 TButton[1] = (Button)findViewById(R.id.Button01);
 TButton[2] = (Button)findViewById(R.id.Button02);
 TButton[3] = (Button)findViewById(R.id.Button03);

up to 36.

like image 687
Tim Wayne Avatar asked Dec 17 '22 02:12

Tim Wayne


1 Answers

The OnClickListener is going to receive the button itself, such as R.id.Button01. It's not going to give you back your array index, as it knows nothing about how you have references to all the buttons stored in an array.

You could just use the button that is passed into your onClickListener directly, with no extra lookups in your array needed. Such as:

void onClick(View v)
{
   Button clickedButton = (Button) v;

   // do what I need to do when a button is clicked here...
   switch (clickedButton.getId())
   {
      case R.id.Button01:
          // do something
          break;

      case R.id.Button01:
          // do something
          break;
   }
}

If you are really set on finding the array index of the button that was clicked, then you could do something like:

void onClick(View v)
{
   int index = 0;
   for (int i = 0; i < buttonArray.length; i++)
   {
      if (buttonArray[i].getId() == v.getId())
      {
         index = i;
         break;
      }
   }

   // index is now the array index of the button that was clicked
}

But that really seems like the most inefficient way of going about this. Perhaps if you gave more information about what you are trying to accomplish in your OnClickListener I could give you more help.

like image 74
Mark B Avatar answered Dec 27 '22 04:12

Mark B