Android:在调用函数之前实现 1 秒间隔计时器 [英] Android: Implement a 1 second interval timer before calling a function

查看:29
本文介绍了Android:在调用函数之前实现 1 秒间隔计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在我重置游戏之前引入 1 秒的暂停 (resetGame()).按下按钮后.bAnswer1 文本确实等于 ansewrArray[0].在 newQuestionTimer() 中设置的 1 秒延迟后,应用程序强制关闭.

I am trying to introduce a 1 second pause before I reset the game (resetGame()). After a button has been pressed. bAnswer1 text does equal ansewrArray[0]. The App force closes after the 1 second delay set in newQuestionTimer().

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);
}

推荐答案

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

You are updating ui from a timer which runs on a background thread. Ui can be updated only on the ui thread.

您可以使用处理程序

   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);

这篇关于Android:在调用函数之前实现 1 秒间隔计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆