gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:55:47 25 4
gpt4 key购买 nike

我如何设置 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com