Android開發,Toast重複顯示(顯示時間過長)解決方法【囧事屋】

Toast是Android中用來顯示信息的一種機制,和Dialog不一樣,Toast沒有焦點,並且Toast顯示的時間有限,必定時間後就會自動消失。 post

Toast通常用來提示用戶的誤操做。可是若是同時顯示多個Toast信息時,系統會將這些Toast信息放到隊列中,等前一個Toast信息顯示關閉後纔會顯示下一個Toast信息。當用戶在某些狀況下,誤操做屢次時,使用 Toast提示會出現不少個Toast依次顯示,在頁面上停留很長時間,用戶體驗很很差!
爲了解決這一問題,每次建立Toast時先作一下判斷,若是前面有Toast在顯示,只需調用Toast中的setText()方法將要顯示的信息替換便可。
代碼以下:
自定義CustomToast 類:
public class CustomToast { spa

private static Toast mToast;
private static Handler mHandler = new Handler();
private static Runnable r = new Runnable() {
public void run() {
mToast.cancel();
}
}; 

public static void showToast(Context mContext, String text, int duration) { xml

mHandler.removeCallbacks(r);
if (mToast != null)
mToast.setText(text);
else
mToast = Toast.makeText(mContext, text, Toast.LENGTH_SHORT);
mHandler.postDelayed(r, duration); 隊列

mToast.show();
} rem

public static void showToast(Context mContext, int resId, int duration) {
showToast(mContext, mContext.getResources().getString(resId), duration);
} get

}
顯示Toast代碼:CustomToast.showToast(getBaseContext(), "提示信息", 1000);
由於通常提示信息都是放在strings.xml中,因此爲了方便使用,又寫了個方法:
public static void showToast(Context mContext, int resId, int duration) {
showToast(mContext, mContext.getResources().getString(resId), duration);
} string

相關文章
相關標籤/搜索