---
title: "android 关于Toast重复显示解决方法"
author: "JustOneCoder"
date: "2013-03-01T10:20:00Z"
tags: []
slug: "android-toast"
draft: false
lastmod: "2013-07-09T18:14:51Z"
id: 1902114
url: "https://justonecoder.iteye.com/blog/1902114"
---

**解决思路：** 不用计算Toast的时间之类的，就是定义一个全局的成员变量Toast, 这个Toast不为null的时候才去make,否则直接setText.为了按返回键后立即使Toast不再显示，重写父类Activity的onBackPressed()方法里面去cancel你的Toast即可.

**代码：**

```
private Toast mToast;
    public void showToast(String text) {  
        if(mToast == null) {  
            mToast = Toast.makeText(TestActivity.this, text, Toast.LENGTH_SHORT);  
        } else {  
            mToast.setText(text);    
            mToast.setDuration(Toast.LENGTH_SHORT);  
        }  
        mToast.show();  
    }  
      
    public void cancelToast() {  
            if (mToast != null) {  
                mToast.cancel();  
            }  
        }  
      
    public void onBackPressed() {  
            cancelToast();  
            super.onBackPressed();  
        }  
```

如果哪位有更好的方法，请不吝分享，谢谢