Android中的Toast重复显示的问题

转自:http://blog.csdn.net/jiangwei0910410003/article/details/17096699

Android Toast 跳转页面时立马让他消失

Toast是Android中用来显示信息的一种机制,和Dialog不一样的是,Toast是没有焦点,而且Toast显示的时间有限,过一定的时间就会自动消失。
Toast一般用来提示用户的误操作。但是如果同时显示多个Toast信息提示框,系统会将这些Toast信息提示框放到队列中,等前一个Toast信息提示框关闭后才会显示下一个Toast信息提示框。当用户在某些情况下,误操作多次时,使用 Toast提示会出现很多个Toast依次显示,在页面上停留很长时间,用户体验很不好!
为了解决这一问题,每次创建Toast时先做一下判断,如果前面有Toast在显示,只需调用Toast中的setText()方法将要显示的信息替换即可。
代码如下:
自定义CustomToast 类:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public class CustomToast {  
  2.     private static Toast mToast;  
  3.     private static Handler mHandler = new Handler();  
  4.     private static Runnable r = new Runnable() {  
  5.         public void run() {  
  6.             mToast.cancel();  
  7.         }  
  8.     };  
  9.     public static void showToast(Context mContext, String text, int duration)        
  10.         mHandler.removeCallbacks(r);  
  11.         if (mToast != null)  
  12.             mToast.setText(text);  
  13.         else  
  14.             mToast = Toast.makeText(mContext, text, Toast.LENGTH_SHORT);  
  15.         mHandler.postDelayed(r, duration);  
  16.         mToast.show();  
  17.     }  
  18.     public static void showToast(Context mContext, int resId, int duration) {  
  19.         showToast(mContext, mContext.getResources().getString(resId), duration);  
  20.     }  
  21.   
  22. }  
显示Toast代码:CustomToast.showToast(getBaseContext(), "提示信息", 1000);
因为一般提示信息都是放在strings.xml中,所以为了方便使用,又写了个方法:
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public static void showToast(Context mContext, int resId, int duration) {  
  2.         showToast(mContext, mContext.getResources().getString(resId), duration);  
  3.     }  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值