倒计时期间的setText

时间:2012-07-30 15:02:58

标签: android android-layout android-widget

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

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);

这是logcat:

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)

我希望你能提供帮助。 感谢

2 个答案:

答案 0 :(得分: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问题链接的想法相同......好吧,无论如何都是这样。

答案 1 :(得分:0)

使用TimerTask代替此。根据文档,The TimerTask class represents a task to run at a specified time. The task may be run once or repeatedly。正是你在寻找什么。可以找到使用TimerTask的示例here