[英]Knowing which button was clicked in Android
I am making an app which will contain 81 buttons on the same layout. 我正在制作一个将在相同布局上包含81个按钮的应用程序。 They are all referred as an object I created called "Tile".
它们全都称为我创建的称为“ Tile”的对象。 Problem is those tiles are stored in an array, so I need to know which button was clicked in an int format to be able to call a tile (
tiles[??]
). 问题是这些图块存储在数组中,因此我需要知道以int格式单击了哪个按钮才能调用图块(
tiles[??]
)。 I am using an onClick(View v)
method. 我正在使用
onClick(View v)
方法。 Also I have tried this: 我也试过这个:
Log.i("Tile", v.getId() + "was clicked")
The result it gave me in the logcat was a really long integer. 它在logcat中给我的结果是一个非常长的整数。
So how can I know which button was clicked in a number format? 那么如何知道数字格式单击了哪个按钮? And what is the relationship between the casual id (
R.id.tile1
) and this long integer, as it could help because it is already a number? 临时id(
R.id.tile1
)和这个长整数之间的关系是什么,因为它已经是一个数字,所以可能会有所帮助?
PS: I know I could use Switch to assign each id to an integer, but as they are 81, it will be a waste of time and will make the code very complicated. PS:我知道我可以使用Switch将每个id分配给一个整数,但是因为它们是81,这将浪费时间,并使代码非常复杂。
I hope you can use tag option. 希望您可以使用标签选项。 You can set the tag for a view by view.setTag(1) and then on click event you can get back the tag set using view.getTag().
您可以通过view.setTag(1)设置视图的标签,然后在单击事件时可以使用view.getTag()获取标签集。
In android we can use the id of the button for getting the click event in on click listener. 在android中,我们可以使用按钮的ID来获取Click监听器中的click事件。
Say you have, 5 Buttons: Make sure your Activity/Fragment implement OnClickListener 假设您有5个按钮:确保您的Activity / Fragment实现OnClickListener
// in OnCreate //在OnCreate中
Button mClickButton1 = (Button)findViewById(R.id.clickButton1);
mClickButton1.setOnClickListener(this);
Button mClickButton2 = (Button)findViewById(R.id.clickButton2);
mClickButton2.setOnClickListener(this);
Button mClickButton3 = (Button)findViewById(R.id.clickButton3);
mClickButton3.setOnClickListener(this);
Button mClickButton4 = (Button)findViewById(R.id.clickButton4);
mClickButton4.setOnClickListener(this);
Button mClickButton5 = (Button)findViewById(R.id.clickButton5);
mClickButton5.setOnClickListener(this);</br>
//after this you will override the onclick method from OnClickListener //在此之后,您将覆盖OnClickListener中的onclick方法
public void onClick(View v) {
switch (v.getId()) {
case R.id.clickButton1: {
// do something for button 1 click
break;
}
case R.id.clickButton2: {
// do something for button 2 click
break;
}
//.... etc
}
}
You can use button.setTag(position) to set position as tag. 您可以使用button.setTag(position)将位置设置为标签。
And when onclick called get that tag value. 并在调用onclick时获取该标记值。
public void onclick(View v){
int position = Integer.parseInt(v.getTag().toString());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.