我想每隔 5 秒更改一次 TextView 的字符串。所以我写道:
Intent intent = getIntent();
int kutisu = Integer.parseInt(intent.getStringExtra("kutisu"));// the number of times
int max = Integer.parseInt(intent.getStringExtra("max"));
int speed = 5000;// 5 seconds
int[] sum=new int[kutisu]; // After finished count, I want to ask for a total
int answer = 0;
for(int i=0;i<=kutisu;i++){
sum[i]=new java.util.Random().nextInt(max);
tv.setText(sum[i]); //tv is a TextView
try {
Thread.sleep(speed); // stop
} catch (InterruptedException e) {
e.printStackTrace();
}
}
但是字符串在运行时并没有改变。如何每 5 秒更改一次 TextView 的字符串?
最佳答案
使用timerTask
public void startTimer() {
//set a new Timer
timer = new Timer();
//initialize the TimerTask's job --> change yourView text data
initializeTimerTask();
//schedule the timer, after the first 5000ms the TimerTask will run every 10000ms
timer.schedule(timerTask, 5000, 10000); //
}
你也可以使用postDelayed
,要让它以5秒的间隔连续运行,你需要调用postDelayed
作为嵌套再次使用您的 Run 方法
handler.postDelayed(new Runnable() {
public void run() {
Log.d("MyActivity", "Ding Ding");
// --> change yourView text data
//calling postdelayed again
handler.postDelayed(this, 5000); //added this line
}
}, 5000);
关于java - 我想每隔 5 秒更改 TextView 的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41198821/