android之Toast多次提示延时处理

学习android的人应该都明白Toast是用来做做什么的,在这里就不多说了。

Toast提示出现后会停留一段时间,在这段时间内再次执行Toast会有时间延迟,即上一次提示消失后下一次才出现。这时我们希望信息能及时更新。

解决思路:当前没有提示信息时正常执行;当前有提示信息时新信息覆盖原来的信息。

法一:创建一个ToastShow类,用于封装此功能

import android.content.Context;
import android.view.Gravity;
import android.widget.Toast;

public class ToastShow { 
    private Context context;  //在此窗口提示信息

    private Toast toast = null;  //用于判断是否已有Toast执行
    public ToastShow(Context context) { 
         this.context = context; 
    } 
    public void toastShow(String text) { 
        if(toast == null) 
        { 
            toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);  //正常执行
        } 
        else { 
            toast.setText(text);  //用于覆盖前面未消失的提示信息
        } 
        toast.show();  
    } 
} 

在需要此功能的窗口中使用

ToastShow toast = new ToastShow(this);
toast.toastShow("提示信息");

法二:创建一个ToastShow类,用于封装此功能

import android.content.Context;
import android.widget.Toast;

/**
 * 自定义Toast
 * @author Administrator
 *
 */
public class ToastUtils {

    protected static Toast toast   = null;
    private static String oldMsg;
    private static long oneTime = 0;
    private static long twoTime = 0;

    public static void showToast(Context context, String s){      
        if(toast==null){   
            toast =Toast.makeText(context, s, Toast.LENGTH_SHORT);  
            toast.show();  
            oneTime=System.currentTimeMillis();  
        }else{  
            twoTime=System.currentTimeMillis();  
            if(s.equals(oldMsg)){  
                if(twoTime-oneTime>Toast.LENGTH_SHORT){  
                    toast.show();  
                }  
            }else{  
                oldMsg = s;  
                toast.setText(s);  
                toast.show();  
            }         
        }  
        oneTime=twoTime;  
    }  

    public static void showToast(Context context, int resId){     
        showToast(context, context.getString(resId));  
    }  
}

在需要此功能的窗口中使用

ToastUtils.showToast(this, "提示信息");
原文地址:https://www.cnblogs.com/kangweifeng/p/4887465.html