项目中经常使用吐司的小伙伴可能会有这样的一个困扰:当退出当前Activity或Fragment后,上一个页面中的吐司仍然没有消失,这样带来了很不好的用户体验。之前测试妹子给我提过这个改进意见,我当时装模作样的说这是系统级别的吐司,即使页面退出也要弹的,不能控制它的消失@¥()*&……¥#!#。事后细品觉得自己好Low,于是翻看了Toast的源码。
/**
* Close the view if it's showing, or don't show it if it isn't showing yet.
* You do not normally have to call this. Normally view will disappear on its own
* after the appropriate duration.
*/
public void cancel() {
mTN.cancel();
}
能读懂第一句就足够了:如果view(吐司)正在显示就关掉它。
原来谷歌就为我们提供了隐藏吐司的方法,这么简单的api我咋就没用过呢?哦,原来是我使用吐司的姿势不对,通常我们是这样使用吐司的:
Toast.makeText(context, “春江潮水连海平,海上明月共潮生”, Toast.LENGTH_LONG).show();
让我们来看一下show方法:
public void show() {
if (mNextView == null) {
throw new RuntimeException("setView must have been called");
}
...
}
show方法是将吐司吐出去的api,返回值是void,所以我们拿不到吐司对象,谈何调用cancel()方法呢?那么我们是不是这样写:
//创建吐司对象
Toast toast = Toast.makeText(context, "滟滟随波千万里,何处春江无月明", Toast.LENGTH_LONG);
//显示吐司
toast.show();
当我们需要隐藏吐司的时候,调用:
toast.cancel();
看起来是行了,不过为了方便自己和他人使用,最好再封装一下:
//吐司工具类
public class ToastUtil {
private static Toast mToast;
public static void showShort(Context context, String text) {
if (null == context) return;
if (null == mToast) {
mToast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
} else {
mToast.setText(text);
mToast.setDuration(Toast.LENGTH_SHORT);
}
mToast.show();
}
public static void showShort(Context context, int resId) {
if (null == context) return;
if (null == mToast) {
mToast = Toast.makeText(context, resId, Toast.LENGTH_SHORT);
} else {
mToast.setText(context.getResources().getString(resId));
mToast.setDuration(Toast.LENGTH_SHORT);
}
mToast.show();
}
public static void showLong(Context context, String text) {
if (null == context) return;
if (null == mToast) {
mToast = Toast.makeText(context, text, Toast.LENGTH_LONG);
} else {
mToast.setText(text);
mToast.setDuration(Toast.LENGTH_LONG);
}
mToast.show();
}
public static void showLong(Context context, int resId) {
if (null == context) return;
if (null == mToast) {
mToast = Toast.makeText(context, resId, Toast.LENGTH_LONG);
} else {
mToast.setText(context.getResources().getString(resId));
mToast.setDuration(Toast.LENGTH_LONG);
}
mToast.show();
}
public static void cancel() {
if (null != mToast) {
mToast.cancel();
mToast = null;
}
}
}
最后在你的BaseActivity的onDestory();中,调用cancel方法就好,如果觉得消失响应不明显的,在onPause()里调用,效果立竿见影。