因此,我创建了一个 java 类来实现 onClickListener
,并在该类中编写了 onClick
公共(public)方法。在此方法之外,我创建了一个 int 对象,并且我想在 onClick
方法内修改该对象。我还通过检查其他类似的SO问题进行了很多研究,并且尝试了很多事情,例如将对象创建为公共(public)int,或将其设为私有(private)int 并有另一个方法来更改它,然后在 onClick 中调用此方法。然而,似乎没有什么效果。
下面显示的代码将 int 对象创建为私有(private) int 并命名为 turn
。为了在 onClick
内更改它,我首先创建了一个名为 changeTurn
的公共(public)方法来修改它,然后在 onClick
内调用此方法。
public class TicTacToe implements View.OnClickListener {
Button buttons[] = new Button[9];
TextView result;
public TicTacToe(Button[] buttonList, TextView text) {
buttons = buttonList;
result = text;
}
//public void
private int turn = 1; // The object that needs to be modified in onCLick
@Override
public void onClick(View v) {
Button b = (Button) v;
if((((Button) v).getText() != "X") && (((Button) v).getText() != "O")) {
if(this.turn == 1) {
b.setText("X");
changeTurn(); // ***Should change the value of turn***
result.setText("Turn is: " + this.turn);
}
if(this.turn == 2) {
b.setText("O");
changeTurn(); // ***Should change the value of turn***
result.setText("Turn is: " + turn);
}
}
}
public void changeTurn() {
if(this.turn == 1) {
this.turn = 2;
}
if(this.turn == 2) {
this.turn = 1;
}
}
}
根据我的尝试,每次我单击 9 个按钮中的任何一个时,程序仅在第一个 if 内运行,这些按钮的 setOnClickListeners 连接到此 onClick 方法。另外,当我打印出来时,turn的值始终为1,这基本上意味着它的值不会被onClick方法内的changeTurn改变。
有关应用程序的一般信息:我正在尝试在带有 9 个按钮的 3x3 网格中制作井字游戏。因为会有 2 个玩家,所以我尝试使用这个 turn 整数来跟踪轮到谁按下按钮。如果turn为1,按钮的文本将更改为X,如果turn为2,则更改为O。现在,每次我按下按钮,它总是更改为X。
我非常感谢任何帮助或想法。
最佳答案
您将转弯设置为 2,然后立即将其设置回 1。
// turn == 1
if(this.turn == 1) { // true
this.turn = 2; // turn == 2
}
if(this.turn == 2) { // now true!
this.turn = 1; // turn == 1
}
最简单的方法是仅在跳过第一个 block 时才输入第二个 block ,即:
if(this.turn == 1) {
this.turn = 2;
} else if(this.turn == 2) {
this.turn = 1;
}
或者,如果您希望用更多回合数来扩展 block ,请使用 switch:
switch(this.turn) {
case 1:
this.turn = 2;
break;
case 2:
this.turn = 1;
break;
}
switch 的唯一麻烦是,如果你忘记了break 语句,你最终会遇到不可预测的困惑。
最后,一个简短的建议:如果您尝试创建一个数字循环(1 .. n 然后回到 1),那么您应该考虑模数运算符 (%),例如 x = x % n + 1;
关于java - 无法修改 onClick 方法内的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35541344/