簡體   English   中英

無法在onClick方法中修改變量

[英]Can't modify variable inside onClick method

因此,我創建了一個Java類來實現onClickListener並在該類中編寫了onClick公共方法。 在此方法之外,我創建了一個int對象,並且想要在onClick方法中修改此對象。 我還通過檢查其他類似的SO問題進行了大量研究,並且嘗試了很多事情,例如將對象創建為public int ,或者將其設置為private int並擁有另一種更改它的方法,然后在onClick中調用此方法。 但是,似乎沒有任何效果。

下面顯示的代碼將int對象創建為私有int,並將其命名為turn 要在onClick更改,我首先創建了一個名為changeTurn的公共方法來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方法相關聯),則該程序僅進入第一個內部。 此外,當我將其打印出來時, turn的值始終為1,這基本上意味着其值不會被onClick方法中的changeTurn更改。

有關該應用程序的常規信息:我正在嘗試用9個按鈕在3x3網格中制作井字游戲。 由於會有2位玩家,因此我嘗試使用此回合整數來跟蹤按下按鈕的回合。 如果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
}

最簡單的方法是僅在跳過第一個塊時才輸入第二個塊,即:

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

另外,如果您希望使用更多的圈數來擴展塊,請使用switch:

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

切換的唯一麻煩是,如果您忘記了break語句,最終將導致無法預料的混亂。

最后,有個簡短的建議:如果您試圖創建一個數字循環(1 .. n然后回到1),則應考慮模運算符(%),例如x = x % n + 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);
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM