【问题标题】:Android: Implement a 1 second interval timer before calling a functionAndroid:在调用函数之前实现 1 秒间隔计时器
【发布时间】:2014-04-23 00:29:13
【问题描述】:

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

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

【问题讨论】:

  • 这就是postDelayed 的用途。最有可能您触及来自resetGame 的视图,因此崩溃
  • 发布堆栈跟踪和重置游戏代码
  • public void resetGame() {guess = 0; bAnswer1.setBackgroundColor(Color.TRANSPARENT); bAnswer2.setBackgroundColor(Color.TRANSPARENT); bAnswer3.setBackgroundColor(Color.TRANSPARENT); bAnswer4.setBackgroundColor(Color.TRANSPARENT); }
  • 对我的回复中的乱码表示歉意。
  • @njzk2 我将如何在 newQuestionTimer() 中实现 postDelayed。谢谢

标签: java android timer


【解决方案1】:

您正在从在后台线程上运行的计时器更新 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);

【讨论】:

  • 我确实考虑过使用处理程序,但选择了 timer.schedule。我要去试试这个。谢谢
  • 这成功了,谢谢。在分配的等待时间后将设置为接受的答案。再次感谢。
  • @Seatter 很高兴为您提供帮助。
【解决方案2】:
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

【讨论】:

    猜你喜欢
    • 2013-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-28
    • 1970-01-01
    • 2021-08-07
    • 1970-01-01
    相关资源
    最近更新 更多