Toast重复显示、离开当前界面自动消失问题(已解决)

1.Toast重复显示问题解决

Toast.makeText()这个方法里面new了一个Toast,当我们点击控件弹出Toast时,每次都会创建一个新的Toast

public static boolean isShow = true;
public static Toast toast = null;
 /**
 * 短时间显示Toast
 * @param message
 */
public static void showShort(CharSequence message) {
    if (TextUtils.isEmpty(message))
        return;
    if (isShow) {
        if (toast != null) {
            toast.setText(message);
            toast.setDuration(Toast.LENGTH_SHORT);
        } else {
            toast = Toast.makeText(MainApplication.getApplication(), message, Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
        }
        toast.show();
    }
}


/**
 * 长时间显示Toast 
 * @param message
 */
public static void showLong(CharSequence message) {
    if (TextUtils.isEmpty(message))
        return;
    if (isShow) {
        Toast toast = Toast.makeText(MainApplication.getApplication(), message, Toast.LENGTH_LONG);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }
}


/**
 * 自定义显示Toast时间
 *
 * @param message
 * @param duration
 */
public static void show(CharSequence message, int duration) {
    if (TextUtils.isEmpty(message))
        return;
    if (isShow) {
        Toast toast = Toast.makeText(MainApplication.getApplication(), message, duration);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }
}

/**
 * 使toast不在显示
 */
public static void cancelMyToast() {
    if (toast != null) {
        toast.cancel();
    }
}
2.如果想让Toast在离开当前界面时自动消失,那么就应该在相应的Activity或Fragment的onPause()生命周期方法中调用上述工具类中的cancelMyToast()这个方法,当然你在BaseActivity和BaseFragment中调用更方便
@Override
public void onPause() {
    super.onPause();
    T.cancelMyToast();
}

你可能感兴趣的:(Toast重复显示、离开当前界面自动消失问题(已解决))