首页 > 解决方案 > 如何使我的应用程序延迟并在循环的每次迭代中更新布局的组件

问题描述

我正在制作一个棋盘游戏,如果我有 3 个 AI 玩家和一个用户在玩。当用户按下按钮将其轮到 AI 时,我想添加一个延迟,以便用户可以看到每个 AI 所做的每一个动作。

我已经尝试过线程睡眠和处理程序,但似乎他们无法更新板并在 while 循环的每次迭代中添加延迟。可以在下面找到没有任何尝试添加延迟的代码。内部 while 循环终止后,我需要添加延迟。

public void onClickNextTurn(View view){
    boolean turnFinished;
    findViewById(R.id.btnChangeTurn).setVisibility(View.INVISIBLE);

    while (this.playerTurn<4) {
        this.playerTurn++;
        turnFinished=false;
        while (!turnFinished) {
            diceRoll();
            MoveTriplet result = ai[playerTurn-2].aiTurn(this.boardPieceLocations, this.homeLocations, this.finishLocations, this.roll, playerTurn);
            if (result != null) {
                if (result.getMoveType() == 'b') { //The Artificial Opponent is moving from one home location to the board AND gets to roll again
                    this.homeLocations[playerTurn - 1][result.getPreviousIndex()] = 0;
                    if (this.boardPieceLocations[result.getNextIndex()] != 0)
                        returnPieceHome(this.boardPieceLocations[result.getNextIndex()]);
                    this.boardPieceLocations[result.getNextIndex()] = this.playerTurn;
                    this.homeButtons[playerTurn - 1][result.getPreviousIndex()].setBackgroundColor(getResources().getColor(R.color.colorHoles));
                    this.buttons[result.getNextIndex()].setBackgroundColor(colors[playerTurn - 1]);
                }

因此,如果有人能指出我如何在外部 while 循环的迭代之间添加延迟并同时更新我的​​板的正确方向。提前致谢!

标签: javaandroid

解决方案


尝试查看标准的 Android 动画 API。那些应该为你处理时间并且更流畅——另外,他们会更有效地为你使用 GPU。


推荐阅读