在 android 中让计分器像计时器一样工作

Make a score counter work like a timer in android

我是 Java 的新手,正在开发我的第一个应用程序。我希望分数像计时器一样显示,直到达到玩家的分数。这是我写的代码。

Handler mHandler = new android.os.Handler();
int temp_score = 0;
while(temp_score<=score){
    final String score_string = "" + temp_score;
    mHandler.postDelayed(new Runnable(){
        public void run() {
            scoreTextView.setText(score_string);
        }
    }, 1000);
    temp_score++;
}

它似乎没有用。当我 运行 它时,应用程序会暂停一会儿,然后显示最终分数。它不会在中间步骤中显示它。我从未使用过这种基于时间的功能。有人可以帮我理解为什么会这样吗?另外,有人可以给我链接,我可以在其中阅读更多关于 postDelayed 方法的信息。我不太了解 developer.android 网站,因为我对它还很陌生。

谢谢

试试这个:

Handler mHandler = new android.os.Handler();
int temp_score = 0;
int i = 0;
while(temp_score<=score){
    final String score_string = "" + temp_score++;
    mHandler.postDelayed(new Runnable(){
        public void run() {
            scoreTextView.setText(score_string);
        }
    }, ++i*1000);
}

处理程序基本上是与单个线程关联并能够向其发送消息、post 指令(Runnables)的对象。 postDelayed() 是指定线程上的延迟命令 post。检查link:https://developer.android.com/reference/android/os/Handler.html

您最初的解决方案不起作用,因为您的 while 循环一直持续到它找到玩家的分数,并且它为每一步创建一个延迟的 运行,但是这些 运行ning 如此之快其他所以你只会注意到最后的变化。

  int temp_score = 0;
 Timer.scheduleAtFixedRate(new TimerTask() {
    @Override
    public void run() {
       runOnUiThread(new Runnable() {

            @Override
            public void run() {
                scoreTextView.setText(score_string);
            }
        });


       temp_score++;
    }
  }, 0, UPDATE_INTERVAL);