Toast, often encountered in Android development, but we always encounter a problem, that is, when we use the button to listen to pop toast, if the constant click of the button, will continue to pop toast, and this article is to solve this problem and written.
At the same time, in order to save the app resources and ease of use, you use a singleton mode to implement a custom toast.
(1) Establish the Mytoast class, and define the following member variables, as well as some of the changes:
Private static Final Object Sync_lock = new Object ();p rivate static Toast mtoast;/** context */public static context Context;p Ublic static Context GetContext () {return context;} public static void SetContext (context context) {Mytoast.context = context;}
(2) To create a method to initialize a toast:
/** * Get toast Environment, add lock for Toast * * @param context * @return */private static void Inittoastinstance () {if (mtoast = = null) { Synchronized (Sync_lock) {if (mtoast = = null) {Mtoast = Toast.maketext (Context, "", Toast.length_short);}}}}
The lock is used here, and the double judgment guarantees the uniqueness of the toast and avoids the occurrence of multiple toasts.
(3) Create a method to display toast:
/** * Show Toast * * @param context * Environment * @param text * content */public static void Showtoast (String text, Context cont EXT) {SetContext (context); GetContext () = null && text = null) {inittoastinstance (); Mtoast.setduration ( Toast.length_short); Mtoast.settext (text); Mtoast.show ();}}
(4) Use the following code to display the toast.
Mytoast.showtoast ("Mytoast", mainactivity.this);
(5) Operation effect:
No matter how many times you click the effect in the diagram, not after multiple clicks, another toast appears after a toast disappears.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
[Android] Custom Toast