我有一个textview,我动态地突出显示它(首先突出显示110个字母然后在1秒后突出显示下一个110个字母,依此类推......)。下面是我的代码。
我刚刚创建了后台线程作为计时器,但它根本没有停止。如何在3次迭代后停止计时器?提前谢谢......
int x=0;,y=110//global values
Timer timer = new Timer();
//Create a task which the timer will execute. This should be an implementation of the TimerTask interface.
//I have created an inner class below which fits the bill.
MyTimer mt = new MyTimer();
//We schedule the timer task to run after 1000 ms and continue to run every 1000 ms.
timer.schedule(mt, 1000, 1000);
class MyTimer extends TimerTask {
public void run() {
//This runs in a background thread.
//We cannot call the UI from this thread, so we must call the main UI thread and pass a runnable
if(x==330)
Thread.currentThread().destroy();
runOnUiThread(new Runnable() {
public void run() {
Spannable WordtoSpan = new SpannableString(names[0]);
WordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), x, y, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
x=x+110;
y=y+110;
textView.setText(WordtoSpan);
}
});
}
}
答案 0 :(得分:1)
您是否尝试使用Handler而不是计时器任务?
private static int TIME_OUT = 3000;
// --------------
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
// do your task here
}
}, TIME_OUT);
使用Timer
有一些缺点它只创建单个线程来执行任务,如果任务运行时间太长,其他任务就会受到影响。它不处理由任务抛出的异常,并且线程只是终止,这会影响其他计划任务,并且它们永远不会运行