我需要每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));
}
});
}
}
答案 0 :(得分:2)
int numberOfUpdates = 0;
创建一个检查计数器的递归方法:
public void updateTextView()
{
if(numberOfUpdates < 5)
{
numberOfUpdates++;
textview.postDelayed(new Runnable() {
@Override
public void run ()
{
updateTextView();
}
}, 3000);
}
}
答案 1 :(得分: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.希望有所帮助!