Android之Toast简单实现不循环提示

来源:互联网 发布:淘宝旺旺有卖家版吗 编辑:程序博客网 时间:2024/06/06 09:54

原文地址:http://blog.csdn.net/way_ping_li/article/details/8840955


不知道各位程序猿们在项目中有没有遇到这个问题:点击一个view弹出一个Toast,我们用的方法是Toast.makeText(context, "提示", Toast.LENGTH_SHORT).show(); 但是,细心的人发现了,如果频繁的点击这个view,会发现尽管我们退出了这个应用,还是会一直弹出提示,这显然是有点点小尴尬和恼人的。下面就给大家提供两种方式解决这个问题。

1.封装了一个小小的Toast:

[java] view plaincopy
  1. /** 
  2.  * 不循环提示的Toast 
  3.  * @author way 
  4.  * 
  5.  */  
  6. public class MyToast {  
  7.     Context mContext;  
  8.     Toast mToast;  
  9.   
  10.     public MyToast(Context context) {  
  11.         mContext = context;  
  12.   
  13.         mToast = Toast.makeText(context, "", Toast.LENGTH_SHORT);  
  14.         mToast.setGravity(170, -30);//居中显示  
  15.     }  
  16.   
  17.     public void show(int resId, int duration) {  
  18.         show(mContext.getText(resId), duration);  
  19.     }  
  20.   
  21.     public void show(CharSequence s, int duration) {  
  22.         mToast.setDuration(duration);  
  23.         mToast.setText(s);  
  24.         mToast.show();  
  25.     }  
  26.   
  27.     public void cancel() {  
  28.         mToast.cancel();  
  29.     }  
  30. }  

2.两个直接调用的函数函数:可以放在在Activity中,在需要时直接调用showToast(String or int); 在Activity的onPause()中调用hideToast(),使得应用退出时,取消掉恼人的Toast。

[java] view plaincopy
  1. /** 
  2.  * Show a toast on the screen with the given message. If a toast is already 
  3.  * being displayed, the message is replaced and timer is restarted. 
  4.  *  
  5.  * @param message 
  6.  *            Text to display in the toast. 
  7.  */  
  8. private Toast toast;  
  9. private void showToast(CharSequence message) {  
  10.     if (null == toast) {  
  11.         toast = Toast.makeText(this, message,  
  12.                 Toast.LENGTH_LONG);  
  13.         toast.setGravity(Gravity.CENTER, 00);  
  14.     } else {  
  15.         toast.setText(message);  
  16.     }  
  17.    
  18.     toast.show();  
  19. }  
  20.    
  21. /** Hide the toast, if any. */  
  22. private void hideToast() {  
  23.     if (null != toast) {  
  24.         toast.cancel();  
  25.     }  

原创粉丝点击