D
D
Danil Grishchenko2015-11-15 01:05:38
Java
Danil Grishchenko, 2015-11-15 01:05:38

How can I make the program work in turn in a method using the Thread.sleep() operator?

The program requires that one picture is highlighted, a couple of seconds pass, and another picture is highlighted. I do this using the Thread.sleep(2000) operator, but the method (program) immediately shows the last picture with a delay of 2 seconds. As if he did everything in his method, but the output gives everything that is left. Code snippet:

but.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String vz = otv1.getText().toString();
                int otv11 = Integer.parseInt(vz);
                if (sum == otv11) {
                    txt3.setText("Правильно, вы угадали!");
                    im.setImageDrawable(getResources().getDrawable(R.drawable.fon1));
                } else {
                    txt3.setText("Неправильно, правильный ответ: " + sum + ".");
                    im.setImageDrawable(getResources().getDrawable(R.drawable.fon2));
                }
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                im.setImageDrawable(getResources().getDrawable(R.drawable.fon));
            }
        });

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alecxandrys, 2015-11-16
@kart_green

It is not necessary to slow down the main thread in this way.
It would be much more correct to use Timer.shedule and give it a TimerTask

but.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String vz = otv1.getText().toString();
                int otv11 = Integer.parseInt(vz);
                if (sum == otv11) {
                    txt3.setText("Правильно, вы угадали!");
                    im.setImageDrawable(getResources().getDrawable(R.drawable.fon1));
                } else {
                    txt3.setText("Неправильно, правильный ответ: " + sum + ".");
                    im.setImageDrawable(getResources().getDrawable(R.drawable.fon2));
                }
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
        Timer timer = new Timer("change");
        Task task = new Task();
        timer.schedule(task, 2000);
            }
        });
}

class Task extends TimerTask {
    @Override
    public void run() {
         im.setImageDrawable(getResources().getDrawable(R.drawable.fon));
        }
}

Something like this

M
MiiNiPaa, 2015-11-15
@MiiNiPaa

Similar question and answer on StackOverflow

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question