Toast短时间内多次显示同一个提示信息只显示一次

有时候点击某个控件的时候需要弹出提示框,比如一个控件有判空操作,连续多次点击多少次就会提示多少次,用户体验就会很差

public class ToastUtils {

    private static Toast toast;
    private static long oneTime = 0;
    private static long twoTime = 0;
    private static CharSequence info = "";

    /***显示*/
    public static void show(Context context, CharSequence text) {
        show(context, text, Toast.LENGTH_SHORT);
    }

    private static void show(Context context, CharSequence text, int duration) {
        try {
            if (toast == null) {
                toast = Toast.makeText(context, text, duration);
                toast.show();
                oneTime = System.currentTimeMillis();
            }else{
                twoTime = System.currentTimeMillis();
                if (info.equals(text)){
                    if (twoTime - oneTime > Toast.LENGTH_SHORT){
                        toast.show();
                    }
                }else{
                    info = text;
                    toast.setText(text);
                    toast.show();
                }
            }
            oneTime = twoTime;
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}

你可能感兴趣的:(Android)