Search code examples
androidwaitrunnable

How can I wait for a period of time after a button is clicked?


So I have an activity which runs a simple snakes and ladders game, and I want to allow the player to click a button and move, which would subsequently be followed by the computer moving. My problem is, that once the player moves, the computer immediately makes its move.

Instead I want the activity to wait before the computer makes its move. I've looked around a lot and found that waiting involves using a thread, but I have failed to implement it without my app crashing

My attempt at declaring a thread:

final Runnable runnable = new Runnable()  {
        @Override
        public void run()
        {
            while (true)
            {

                try
                {
                    Thread.sleep(5000);
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
            }

        }
    };

    Thread thread= new Thread(runnable);

My onClick() method for the button:

Button rollButton = (Button) (findViewById(R.id.rollButton));
    rollButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //executes only if current player is a human
            if(GAME_BOARD.getCurrentPlayer().isHuman()) {

                GAME_BOARD.rollDie(); // rolls the die
                showDie(GAME_BOARD); // displays die on screen      
                GAME_BOARD.move();  // moves the player and sets next player as current player
                playerTurn.setText(GAME_BOARD.getCurrentPlayer().getName() +"'s turn");// sets TextView to display who's player's turn it is
                thread.start();  

                if(!GAME_BOARD.getCurrentPlayer().isHuman()) {

                    GAME_BOARD.rollDie();
                    showDie(GAME_BOARD);
                    GAME_BOARD.move();
                    playerTurn.setText(GAME_BOARD.getCurrentPlayer().getName() +"'s turn");                 
                }   
            }

        }
    });

So again, my question is, how do I make it so that before the second if statement executes, the activity waits, say 4 seconds?


Solution

  • you can use an Handler.postDeleayed. You have to provide a Runnable to execut and the delay period in milliseconds. The Runnable will be executed on the UI Thread