How Android dynamically controls the display and hiding of Toast

Display and hide of Toast dynamically controlled by Android

We know that Toast information will be automatically hidden after it is displayed for a period of time, because it has a Toast queue, and the system will take one Toast out of the queue in turn.

In the recent development, I have encountered a problem. In the process of setting a function, display the Toast box information. Only after the setting is successful, can I hide the Toast box!

Toast only provides two options: toast.length'short'and toast.length'long ', so what should we do?

Check the method provided by Toast and find that cancel() is used to hide the current Toast. With timer, it is easy to realize the function I want!

Key code:

public class CustomToast {
    private static final String TAG = "CustomToast";
    private Context mContext;
    private Toast mToast;
    private final int ALWAYS_SHOW = 0;
    private boolean mIsNeedHide = false;
    private Handler mHandler = new Handler(){
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case ALWAYS_SHOW:
                    if (mToast != null) {
                        if (!mIsNeedHide) {
                            Log.d(TAG,"toast show");
                        } else {
                            Log.d(TAG,"toast hide");
                            mIsNeedHide = false;

    public CustomToast(Context context){
        mContext = context;

    public void alwaysShow(final String text){
        //Prevent using Crash by bouncing Toast in child threads
        CustomToastApplistion.getInstance().runUITask(new Runnable() {
            public void run() {
                if (mToast == null) {
                    mToast = Toast.makeText(CustomToastApplistion.getInstance(), text, Toast.LENGTH_SHORT);
                } else {

     * Hide Toast box
    public void hide(){
        this.mIsNeedHide = true;

design sketch:

Full Demo address

Code address

Tags: Android

Posted on Sun, 03 May 2020 15:16:43 -0700 by CloudSex13