[英]Do I need to add many methods, or is it possible to call one method
我有一个tic tac toe应用程序,我想知道是否可以将所有tic tac toe按钮设置为一个on_click事件,然后创建一个变量以获取被单击按钮的ID,然后将其作为参数传递另一个将执行实际功能的方法,还是我需要为每个按钮创建不同的on_click事件?
You can do something like this, and add as many "cases" as needed: 您可以执行以下操作,并根据需要添加尽可能多的“案例”:
View.OnClickListener sharedClickHandler = new View.OnClickListener() {
public void onClick(View view) {
switch(view.getId()) {
case R.id.button1:
// handle first button
break;
case R.id.button2:
// handle second button
break;
}
}
}
You can just use one listener - the onClick
method takes a View
parameter, which is the view that was clicked on. 您只能使用一个侦听器onClick
方法采用一个View
参数,该参数是被单击的视图。 You can then find out which of your buttons that was: 然后,您可以找出哪个按钮是:
View.OnClickListener sharedClickHandler = new View.OnClickListener() {
public void onClick(View view) {
int id = view.getId();
// Do the right thing based on the ID
}
}
Exactly how you do what you need to do based on the ID is up to you. 确切的操作取决于您的ID。 For simple examples you could just use a switch/case statement; 对于简单的例子,您可以只使用switch / case语句; in other cases if you're mapping from ID to something else (a mutable object representing game state for example) you could use a Map<Integer, GameObject>
and just get the right one... 在其他情况下,如果您要从ID映射到其他对象(例如,代表游戏状态的可变对象),则可以使用Map<Integer, GameObject>
并获取正确的对象...
hello you can use the same click event for button, you can attach for example an integer as a tag to the button so that you can know which button was clicked and handle accordingly. 您好,您可以对按钮使用相同的click事件,您可以在按钮上附加例如整数作为标记,以便您知道单击了哪个按钮并进行相应的处理。
button1.setTag(1);
button2.setTag(2);
button3.setTag(3);
button1.setOnClickListener(buttonClick());
button2.setOnClickListener(buttonClick());
button3.setOnClickListener(buttonClick());
public View.OnClickListener buttonClick(){
View.OnClickListener click = new View.OnClickListener() {
@Override
public void onClick(View v) {
int numberClicked = v.getTag();
//You have now the button clicked
}
};
return click;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.