【问题标题】:Android which button index from array was pressedAndroid 按下了数组中的哪个按钮索引
【发布时间】:2011-01-27 11:23:51
【问题描述】:

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

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

最多 36 个。

【问题讨论】:

    标签: android arrays button


    【解决方案1】:

    您可以设置标签值并在点击时获取标签:

    TButton[1] = (Button)findViewById(R.id.Button01);
    TButton[1].setTag(1);
    
    
    onClick(View v)
    {
      if(((Integer)v.getTag())==1)
      {
       //do something
      }
    }
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 那是票。我只想要索引号 - 开关会做一些事情 R.id.Button01: index = 1。谢谢 mbaird!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多