How to put a wait time for the code to execute?

2

I'm playing a little game of memory, more like learning in Java myself. I'll introduce the code and then explain the question.

 private void testar (ImageView img, int resultado1, int resultado2) {

    if(resultado1 != resultado2 && resultado2 != 12){
        teste.setText("diferente");
        //quero colocar um temporizador aqui!!!
        img.setImageResource(R.drawable.cartatras);

        if (flag == 1){
            carta1.setImageResource(R.drawable.cartatras);
        } else if (flag == 2) {
            carta2.setImageResource(R.drawable.cartatras);
        } else if (flag == 3) {
            carta3.setImageResource(R.drawable.cartatras);

Basically it is a function that I did that compares the first and second card chosen by the user, and if it is different, it points the card to the two chosen by the user.

The problem is this: I call this method in OnClick from the moment the second letter is chosen, but it does not give you any time to see what the second letter is, it already directs it as cartatras and the user does not have time to see which card it was.

So I need some way to make the code wait a bit, so the user first sees what the letter was, and then set it face down. I tried to use Thread.sleep in try / catch , but it did not work.

    
asked by anonymous 10.11.2018 / 17:40

2 answers

1

I do not know if a timer would be the best option, maybe waiting for the user's click would be more usual, but anyway. I believe the postDelayed method of the Handler class can help you: link

handler = new Handler();

// tarefa postergada por 5000 milissegundos
handler.postDelayed(new Runnable() {
    public void run() {
        fazAlgumaCoisa();
    }
}, 5000);
    
10.11.2018 / 19:27
0

Uses TimeUnit link

TimeUnit.SECONDS.sleep(30);

In the parameter is only how many seconds should be expected to perform a next action.

    
10.11.2018 / 20:05