2

我不明白为什么我会收到此错误。我一直在查看不同的代码,我使用了这个 Timer one,因为坦率地说我不知道​​如何使用 Java Timers,现在它只会让我的应用程序崩溃。请帮忙吗?

timer.schedule(new TimerTask() {
        public void run() {

            findViewById(R.id.progressBar1).setVisibility(View.GONE);
            findViewById(R.id.loadingn).setVisibility(View.GONE);

            findViewById(R.id.tuser).setVisibility(View.VISIBLE);
            findViewById(R.id.tpass).setVisibility(View.VISIBLE);
            loginbutton.setVisibility(View.VISIBLE);
            findViewById(R.id.username).setVisibility(View.VISIBLE);
            findViewById(R.id.pass).setVisibility(View.VISIBLE);
            timer.cancel();
        }
    }, 5000, 5000);

我忘了...这是错误代码:

12-24 05:53:19.639: E/AndroidRuntime(9887):     FATAL EXCEPTION: Timer-0
12-24 05:53:19.639: E/AndroidRuntime(9887):     android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
12-24 05:53:19.639: E/AndroidRuntime(9887):     at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:4176)
12-24 05:53:19.639: E/AndroidRuntime(9887):     at android.view.ViewRootImpl.invalidateChild(ViewRootImpl.java:749)
12-24 05:53:19.639: E/AndroidRuntime(9887):     at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:805)
12-24 05:53:19.639: E/AndroidRuntime(9887):     at android.view.ViewGroup.invalidateChild(ViewGroup.java:4005)
12-24 05:53:19.639: E/AndroidRuntime(9887):     at android.view.View.invalidate(View.java:8591)
12-24 05:53:19.639: E/AndroidRuntime(9887):     at android.view.View.setFlags(View.java:6718)
12-24 05:53:19.639: E/AndroidRuntime(9887):     at android.view.View.setVisibility(View.java:4632)
12-24 05:53:19.639: E/AndroidRuntime(9887):     at info.david.statusbar.MainActivity$1.run(MainActivity.java:43)
12-24 05:53:19.639: E/AndroidRuntime(9887):     at java.util.Timer$TimerImpl.run(Timer.java:284)
4

1 回答 1

4

使用runOnUiThread从 as 访问 Ui 元素TimerTask

timer.schedule(new TimerTask() {
   public void run() {
     Your_Current_Activity.this.runOnUiThread(new Runnable() 
         {
           public void run() 
            {

                   // access UI here
            }

      });
    }
 }, 5000, 5000);
于 2012-12-24T11:05:02.307 回答