[Android] Custom Toast

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.