Android:在调用函数之前实现1秒间隔计时器

时间:2014-03-17 16:56:12

标签: java android timer

我试图在重置游戏之前引入1秒的暂停(resetGame())。按下按钮后。 bAnswer1文本等于ansewrArray [0]。在newQuestionTimer()中设置1秒延迟后,App力会关闭。

import java.util.Timer;
import java.util.TimerTask;

Timer timer = new Timer();

bAnswer1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if(bAnswer1.getText().toString().equals(answerArray[0]))
                {
                    bAnswer1.setBackgroundColor(Color.GREEN);
                    newQuestionTimer();                 
                }
                else
                {
                    bAnswer1.setBackgroundColor(Color.RED);
                    guess++;
                }
            }
        });

public void newQuestionTimer()
{
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            resetGame();
        }
    }, 1000);
}

2 个答案:

答案 0 :(得分:4)

您正在从在后台线程上运行的计时器更新ui。 Ui只能在ui线程上更新。

您可以使用处理程序

   Handler handler = new Handler();
   handler.postDelayed(new Runnable(){
        @Override
        public void run() {
            bAnswer2.setBackgroundColor(Color.TRANSPARENT);           
            bAnswer3.setBackgroundColor(Color.TRANSPARENT);         
            bAnswer4.setBackgroundColor(Color.TRANSPARENT);
        }
    }, 1000);

答案 1 :(得分:0)

new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {

          //your code here
          //you can add a block of code or a function cll

          //myFunction();

        }
    }, 1000);  //setting 1 second delay : 1000 = 1 second

我从这里开始这个样本 http://wiki.workassis.com/android-execute-code-after-10-seconds