不知道各位程式猿們在項目中有沒有遇到這個問題:點擊一個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(); }}