N
N
NameOf Var2017-08-14 01:26:28
Java
NameOf Var, 2017-08-14 01:26:28

How to delay execution by 1-2 seconds?

Create an event handler for the button click. The logic is that when you click on the button, the button itself should light up in a certain color. Did it like this:

@Override
    public void onClick(View v) {
            v.setBackgroundResource(R.drawable.choose_answer);
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
   }

But here, for some reason, the press is first performed, then there is a delay of 2 seconds, then only the color changes.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Z
z0rgoyok, 2017-08-14
@z0rgoyok

postDelayed

A
AStek, 2017-08-14
@AStek

You have blocked the thread of execution.
I think it's worth trying something like this:

@Override
    public void onClick(final View v) {
        new Thread(()->{
            v.setBackgroundResource(R.drawable.choose_answer);
           try {
              Thread.sleep(2000);
           } catch (InterruptedException e) {
              e.printStackTrace();
           }
        }).start();
   }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question