如何在android中设置延迟?

新手上路,请多包涵
public void onClick(View v) {
        // TODO Auto-generated method stub
        switch(v.getId()){
        case R.id.rollDice:
            Random ranNum = new Random();
            int number = ranNum.nextInt(6) + 1;
            diceNum.setText(""+number);
            sum = sum + number;
            for(i=0;i<8;i++){
                for(j=0;j<8;j++){

                    int value =(Integer)buttons[i][j].getTag();
                    if(value==sum){
                        inew=i;
                        jnew=j;

                        buttons[inew][jnew].setBackgroundColor(Color.BLACK);
                                                //I want to insert a delay here
                        buttons[inew][jnew].setBackgroundColor(Color.WHITE);
                         break;
                    }
                }
            }

            break;

        }
    }

我想在更改背景之间的命令之间设置延迟。我尝试使用线程计时器并尝试使用运行和捕获。但它不起作用。我试过这个

 Thread timer = new Thread() {
            public void run(){
                try {
                                buttons[inew][jnew].setBackgroundColor(Color.BLACK);
                    sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

             }
           };
    timer.start();
   buttons[inew][jnew].setBackgroundColor(Color.WHITE);

但它只会变成黑色。

原文由 Kenneth Joseph Paul 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 364
2 个回答

试试这个代码:

 import android.os.Handler;
...
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        // Do something after 5s = 5000ms
        buttons[inew][jnew].setBackgroundColor(Color.BLACK);
    }
}, 5000);

原文由 Tuan Vu 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以使用 CountDownTimer 这比发布的任何其他解决方案都高效得多。您还可以使用其 onTick(long) 方法按时间间隔生成定期通知

看看这个显示 30 秒倒计时的示例

   new CountDownTimer(30000, 1000) {
         public void onFinish() {
             // When timer is finished
             // Execute your code here
     }

     public void onTick(long millisUntilFinished) {
              // millisUntilFinished    The amount of time until finished.
     }
   }.start();

原文由 Sufiyan Ghori 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题