java - 如何在 Android 中使用计时器?

标签 java android timer intervals

我需要按时间间隔收集数据,这里的数据收集是用一个计数整数来模拟的。但我似乎无法收集该整数。我需要在单击一个按钮后开始收集,并在单击另一个按钮时结束收集。有什么想法吗?

package com.example.test.gothedistance;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

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

public class MainActivity extends AppCompatActivity {

Button start, stop;
TextView sumText;
int count;
Timer t;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    start = (Button) findViewById(R.id.startButton);
    stop = (Button) findViewById((R.id.stopButton));
    sumText = (TextView) findViewById(R.id.sumTV);
    t = new Timer();
    count = 0;




    t.scheduleAtFixedRate(
            new TimerTask()
            {
                public void run()
                {
                    count++;

                }
            },0,2000);

  stop.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            t.cancel();
            sumText.setText(count);
        }
    });
}
}

最佳答案

问题可能出在 sumText.setText(count) 行,该行使用 TextView.setText(int resid) 。这意味着它正在寻找等于 count 的 id,而不是显示 count 的值。您需要先将此值转换为整数:

sumText.setText(Integer.toString(count))

关于java - 如何在 Android 中使用计时器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36189338/

相关文章:

javascript - 2 分钟后重定向页面,即使窗口未激活

python - 带音频释放的计时器

java - Selenium中如何在多个地方上传文件?

java - java代码的解释?

android - 在弹出窗口android中的EditText上添加TextChangedListener()

web-scraping - 在 Nixos 上使用 systemd 计时器运行脚本

java - enum.values() - 是返回枚举确定性的顺序

java - 使用纯 Java 与 SSH 服务器通信以进行文件访问

android - Android apk 中的 kotlin/文件夹的用途是什么?

android - AzureDevOps Android Pipeline zipalign - 失败,退出代码为 1