Tim*_*yne 4 arrays android button
如何设置OnClickListener来简单地告诉我从一组按钮中按下了哪个索引按钮.我可以使用数组更改这些按钮的文本和颜色.我这样设置它们.
TButton[1] = (Button)findViewById(R.id.Button01);
TButton[2] = (Button)findViewById(R.id.Button02);
TButton[3] = (Button)findViewById(R.id.Button03);
Run Code Online (Sandbox Code Playgroud)
最多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;
}
}
Run Code Online (Sandbox Code Playgroud)
如果您确实设置了查找单击按钮的数组索引,那么您可以执行以下操作:
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
}
Run Code Online (Sandbox Code Playgroud)
但这似乎是解决这个问题的最低效方式.也许如果您在OnClickListener中提供了有关您要完成的更多信息,我可以为您提供更多帮助.
| 归档时间: |
|
| 查看次数: |
10150 次 |
| 最近记录: |