0

我有一个问题,我无法在倒计时期间设置按钮的文本,这是代码:

begin.setText("Start level 1");
begin.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {

final int delay = 0000; // delay for 5 sec.
final int period = 1000; // repeat every sec.
final Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
    public  void run() {
        begin.setText("" + t);
        t--;
        if(t == 0) {
            timer.cancel()
        }
    }
}, delay, period);

这是日志猫:

android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
07-30 17:27:05.273: E/AndroidRuntime(22543):    at android.view.ViewRoot.checkThread(ViewRoot.java:2802)
07-30 17:27:05.273: E/AndroidRuntime(22543):    at android.view.ViewRoot.requestLayout(ViewRoot.java:594)
07-30 17:27:05.273: E/AndroidRuntime(22543):    at android.view.View.requestLayout(View.java:8128)
07-30 17:27:05.273: E/AndroidRuntime(22543):    at android.view.View.requestLayout(View.java:8128)
07-30 17:27:05.273: E/AndroidRuntime(22543):    at android.view.View.requestLayout(View.java:8128)
07-30 17:27:05.273: E/AndroidRuntime(22543):    at android.widget.RelativeLayout.requestLayout(RelativeLayout.java:254)
07-30 17:27:05.273: E/AndroidRuntime(22543):    at android.view.View.requestLayout(View.java:8128)
07-30 17:27:05.273: E/AndroidRuntime(22543):    at android.view.View.requestLayout(View.java:8128)
07-30 17:27:05.273: E/AndroidRuntime(22543):    at android.widget.TextView.checkForRelayout(TextView.java:5405)
07-30 17:27:05.273: E/AndroidRuntime(22543):    at android.widget.TextView.setText(TextView.java:2712)
07-30 17:27:05.273: E/AndroidRuntime(22543):    at android.widget.TextView.setText(TextView.java:2580)
07-30 17:27:05.273: E/AndroidRuntime(22543):    at android.widget.TextView.setText(TextView.java:2555)
07-30 17:27:05.273: E/AndroidRuntime(22543):    at it.bisemanuDEV.piano.livello1$1$1.run(livello1.java:134)
07-30 17:27:05.273: E/AndroidRuntime(22543):    at java.util.Timer$TimerImpl.run(Timer.java:289)

我希望你能帮忙。谢谢

4

2 回答 2

2

正如@Jug6ernaut 提到的,你不应该使用TimerTask.
相反,您可以尝试使用Handler. 这就是我在计时器中做类似事情的方式。

例如,在你想要调用的计时器中.setText(),执行以下操作:

mHandler.post(new Runnable() {
    @Override
    public void run() {
        begin.setText(gcalendar.get(Calendar.MINUTE)+":"+gcalendar.get(Calendar.SECOND));   
    }
});

它被简单地初始化为Handler mHandler = new Handler()

编辑:刚刚注意到这与您的答案下方评论中发布的其他 SO 问题链接的想法相同......好吧,无论如何都是这样。

于 2012-07-30T15:29:12.350 回答
0

使用 aTimerTask而不是这个。根据文档,The TimerTask class represents a task to run at a specified time. The task may be run once or repeatedly. 正是您正在寻找的。TimerTask可以在此处找到使用 a 的示例。

于 2012-07-30T15:08:09.333 回答