4

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.

2 Answers 2

11

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.

Sign up to request clarification or add additional context in comments.

1 Comment

That was the ticket. I only wanted the index number - the switch do something would be case R.id.Button01: index = 1. Thank you mbaird!
1

You can set Tag value and get the Tag on Click:

TButton[1] = (Button)findViewById(R.id.Button01);
TButton[1].setTag(1);


onClick(View v)
{
  if(((Integer)v.getTag())==1)
  {
   //do something
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.