Android的哪个按钮指数从阵列为pressed阵列、按钮、指数、Android

2023-09-05 11:29:05 作者:如果你觉得你泡得到我,大可以试试,我会让你知道什么叫心想事成

我如何设立一个OnClickListener简单地告诉我哪些索引按钮是从按钮阵列pssed $ P $。我可以改变这些按钮使用阵列的文字和颜色。我现在就写了这个样子。

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

达36。

up to 36.

推荐答案

在OnClickListener将要接收按钮本身,如R.id.Button01。它不会给你回你的数组索引,因为它一无所知,你怎么也得引用的所有存储在一个数组的按钮。

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.

您可以只使用传递到您的onClickListener直接与您的阵列中无需额外的查找按钮。如:

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
}

但是,这真的好像要去这个是最没有效率的方式。或许,如果你给你正在尝试完成您的OnClickListener我可以给你更多的帮助是什么的详细信息。

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.