我需要每2秒从活动中更新TextView 5次。我尝试了postDelayed()和其他东西,并设法每N秒更改一次TextView,但我不知道如何限制重复次数。有什么建议吗?非常感谢。
这是我现在的代码:
onCreate():
Timer timing = new Timer();
timing.schedule(new Updater(textView, textView2), 3000, 3000);
更新程序():
private static class Updater extends TimerTask {
final Random rand = new Random();
private final TextView textView1;
private final TextView textView2;
public Updater(TextView textView1, TextView textView2) {
this.textView1 = textView1;
this.textView2 = textView2;
}
@Override
public void run() {
textView1.post(new Runnable() {
public void run() {
textView1.setText(String.valueOf(rand.nextInt(50) + 1));
textView2.setText(String.valueOf(rand.nextInt(50) + 1));
}
});
}
}
您还可以使用Android SDK中的CountDownTimer:
new CountDownTimer(TOTAL_RUNNING_TIME_IN_MILLIS, TICK_TIME)
{
public void onTick(long millisUntilFinished)
{
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish()
{
mTextField.setText("done!");
}
}.start();
因此,在您的情况下,TICK_TIME应为2*1000,TOTAL_RUNNING_TIME应为5*2*1000。希望能有所帮助!
- 在活动中保留计数器:
int numberOfUpdates = 0;
-
创建一个检查计数器的递归方法:
public void updateTextView() { if(numberOfUpdates < 5) { numberOfUpdates++; textview.postDelayed(new Runnable() { @Override public void run () { updateTextView(); } }, 3000); } }