开发者

Android which button index from array was pressed

开发者 https://www.devze.com 2022-12-23 01:55 出处:网络
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.

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开发者_Python百科);

up to 36.


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.


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
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消