无法在onClick方法中修改变量

时间:2016-02-21 20:06:09

标签: java android onclick android-button

所以,我创建了一个实现onClickListener的java类,在这个类中我编写了onClick公共方法。在这个方法之外,我创建了一个int对象,我想在onClick方法中修改这个对象。我通过检查其他类似的 SO 问题进行了大量研究,我尝试了很多方法,例如将对象创建为 public int ,或者将其设为私有int 并有另一种方法来更改它,然后在onClick中调用此方法。然而,似乎没有任何作用。

下面显示的代码将int对象创建为 private int 并命名为turn。要在onClick中更改它,我首先创建了一个名为changeTurn的公共方法,修改它,然后在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个按钮中的任何一个,其setOnClickListeners连接到这个onClick方法,程序就会在第一个 if 内部进行。此外,当我将其打印出来时, turn 的值始终为1,这基本上意味着onClick方法中的changeTurn不会更改其值。

关于应用程序的一般信息:我正在尝试使用9个按钮在3x3网格中制作一个井字游戏。由于会有2个玩家,我正在尝试使用此整数来跟踪按下按钮的转向。如果turn为1,则按钮的文本变为X,如果turn为2,则变为O.现在,每按一次按钮,它总是变为X.

我真的很感激任何帮助或想法。

2 个答案:

答案 0 :(得分:2)

您将转弯设置为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
}

最简单的方法是只在跳过第一个块时输入第二个块,即:

if(this.turn == 1) {
    this.turn = 2;
} else if(this.turn == 2) {
    this.turn = 1;
}

或者,如果您希望使用更多转数来扩展块,请使用开关:

switch(this.turn) {
    case 1:
        this.turn = 2;
        break;
    case 2:
        this.turn = 1;
        break;
}

切换的唯一问题是,如果你忘记了一个中断语句,你最终会出现无法预测的混乱。

最后,一点建议:如果你试图创建一个数字循环(1 .. n然后又回到1)那么你应该考虑模数运算符(%),如x = x % n + 1;

答案 1 :(得分:1)

尝试像这样使用

final private int[] turn = {0}

然后将代码更改为

if(turn[0] == 1) {
        b.setText("X");
        turn[0]=2; // ***Should change the value of turn***
        result.setText("Turn is: " + turn);
    }
    if(turn[0] == 2) {
        b.setText("O");
        turn[0]=1; // ***Should change the value of turn***
        result.setText("Turn is: " + turn);
    }
相关问题