开发者

How to ensure serial semantics with Toast?

开发者 https://www.devze.com 2023-02-15 14:53 出处:网络
I was reviewing a student\'s program, which had code like this within an Activity: Toast toast = Toast.makeText(this, \"Hello\", Toast.LENGTH_LONG);

I was reviewing a student's program, which had code like this within an Activity:

Toast toast = Toast.makeText(this, "Hello", Toast.LENGTH_LONG);
toast.show();
toast.setText("Goodbye");

This displayed the text "Goodbye", which was initially quite a surprise. I assume this happened because the call to show() merely queues up a request to display the Toast instance and returns before it is actually displayed. The call to setText("Goodbye") mutates the instance before it is displayed.

Two questions:

  1. Is my interpretation correct?
  2. What's the best way to ensure serial semant开发者_如何学JAVAics in the presence of Toast mutation?


When in doubt it's best to consult the source.

Toast internally uses a static reference to INotificationManager and calls it's enqueueToast method every time a Toast.show() is called.

It synchronizes around a List of Toasts so that only one Toast at a time is showed - this is needed if multiple Toast.show() are called then shows them one after another with their set duration.

Since Toasts references are enqueued (actually Toasts internal class TN is), calling setText() changes the enqueued Toast.

0

精彩评论

暂无评论...
验证码 换一张
取 消