2012-09-07 28 views
0

在我的應用程序中,我想取消舊的烤麪包,並顯示新的烤麪包。但它不工作。android 4.0 toast.cancel()效果不好

       Handler postHandler = new Handler();  
         postHandler.post(new Runnable() { 
          @Override 
          public void run() { 

            if (toast != null) { 
             toast.cancel(); 
           toast.maketext(this,"new toast",Toast.LENGTH_LONG); 



            } 
            toast.show(); 

          } 
         }); 


       return false; 
      } 
     }); 

但沒有顯示。

的logcat中顯示:

E/AndroidRuntime(6706): FATAL EXCEPTION: main 
E/AndroidRuntime(6706): java.lang.NullPointerException 
E/AndroidRuntime(6706):  at android.view.View.onAttachedToWindow(View.java:9533) 
E/AndroidRuntime(6706):  at android.view.View.dispatchAttachedToWindow(View.java:9786) 
E/AndroidRuntime(6706):  at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2198) 
E/AndroidRuntime(6706):  at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:957) 
E/AndroidRuntime(6706):  at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2453) 
E/AndroidRuntime(6706):  at android.os.Handler.dispatchMessage(Handler.java:99) 
E/AndroidRuntime(6706):  at android.os.Looper.loop(Looper.java:137) 
E/AndroidRuntime(6706):  at android.app.ActivityThread.main(ActivityThread.java:4424) 
E/AndroidRuntime(6706):  at java.lang.reflect.Method.invokeNative(Native Method) 
E/AndroidRuntime(6706):  at java.lang.reflect.Method.invoke(Method.java:511) 
E/AndroidRuntime(6706):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 
E/AndroidRuntime(6706):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 
E/AndroidRuntime(6706):  at dalvik.system.NativeStart.main(Native Method) 
W/ActivityManager( 183): Force finishing activity com.rk.youming/.Testsurfacevie 
+0

你確定這個錯誤從你的代碼中拋出嗎? – neworld

回答

0

您的代碼是沒有真正意義上的。你參考新的烤麪包,並嘗試cancel()它之前它顯示。如果你想cancel()你必須在引用舊吐司的對象上調用它,而不是新的。如果烤麪包是null你不會取消()(因爲if),但仍然嘗試show(),它將以NPE結束。

+0

謝謝。我想點擊按鈕顯示烤麪包,並顯示在不同的位置。所以我想取消舊的烤麪包,並顯示新的。 – user1643151

+0

吐司排隊,所以除非你真的需要取消舊的,只需顯示新的,就是這樣。 –

+0

我真的需要取消舊的。我需要它在不同的位置敬酒。 – user1643151