不知道各位程序猿们在项目中有没有遇到这个问题:点击一个view弹出一个Toast,我们用的方法是Toast.makeText(context, "提示", Toast.LENGTH_SHORT).show(); 但是,细心的人发现了,如果频繁的点击这个view,会发现尽管我们退出了这个应用,还是会一直弹出提示,这显然是有点点小尴尬和恼人的。下面就给大家提供两种方式解决这个问题。
1.封装了一个小小的Toast:
/**
* 不循环提示的Toast
* @author way
*
*/
public class MyToast {
Context mContext;
Toast mToast;
public MyToast(Context context) {
mContext = context;
mToast = Toast.makeText(context, "", Toast.LENGTH_SHORT);
mToast.setGravity(17, 0, -30);//居中显示
}
public void show(int resId, int duration) {
show(mContext.getText(resId), duration);
}
public void show(CharSequence s, int duration) {
mToast.setDuration(duration);
mToast.setText(s);
mToast.show();
}
public void cancel() {
mToast.cancel();
}
}
2.两个直接调用的函数函数:可以放在在Activity中,在需要时直接调用showToast(String or int); 在Activity的onPause()中调用hideToast(),使得应用退出时,取消掉恼人的Toast。
/**
* Show a toast on the screen with the given message. If a toast is already
* being displayed, the message is replaced and timer is restarted.
*
* @param message
* Text to display in the toast.
*/
private Toast toast;
private void showToast(CharSequence message) {
if (null == toast) {
toast = Toast.makeText(this, message,
Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
} else {
toast.setText(message);
}
toast.show();
}
/** Hide the toast, if any. */
private void hideToast() {
if (null != toast) {
toast.cancel();
}
}