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:
- Is my interpretation correct?
- 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.
精彩评论