Android 按下了数组中的哪个按钮索引

标签 android arrays button

我如何设置 OnClickListener 来简单地告诉我按下了按钮数组中的哪个索引按钮。我可以使用数组更改这些按钮的文本和颜色。我是这样设置的。

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

最多 36 个。

最佳答案

OnClickListener 将接收按钮本身,例如 R.id.Button01。它不会返回数组索引,因为它不知道您如何引用存储在数组中的所有按钮。

您可以直接使用传递给您的 onClickListener 的按钮,不需要在您的数组中进行额外的查找。如:

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

如果你真的想找到被点击按钮的数组索引,那么你可以这样做:

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 中尝试完成的工作的更多信息,我可以为您提供更多帮助。

关于Android 按下了数组中的哪个按钮索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2443730/

相关文章:

Android 4.0.3 模拟器崩溃 : Failed to allocate memory: 8

java - ListView setAdapter 对空对象引用

python - 零填充 3d Numpy 数组

javascript - 如何在 AngularJS 中同步切换按钮内的复选框?

android - PreferenceScreen 的状态列表?

java - 如何在 Android 中从数组中提取字符串?

python - 在 pandas 数据帧上应用条件来过滤数组时出现 FutureWarning

c++ - 你能用大括号在 C++ 的 return 语句中初始化数组吗?

Flutter Progress_state_button - 如何更改按钮状态

swift 3 : button on collectionview