android 項目最佳化之toast提示最佳化
在我們做登陸驗證的時候經常會用到toast來提示使用者輸入內容的錯誤等,很多人都是直接用的
Toast.makeText(LoginActivity.this, "請聯絡小區物管", Toast.LENGTH_SHORT).show();
然而,用這個的時候你會發現我在沒有輸入使用者名稱的時候一直點擊登陸按鈕,程式會一直提示"請輸入使用者名稱"等字樣,然後你不點擊的時候,程式還會提示,直到提示到跟你點擊次數一致時,才會停止提示,這樣給使用者的體驗是極度不好的,所以提供一個toast的類,
public class CustomToast {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 context, String text, int duration) {mhandler.removeCallbacks(r);if (null != mToast) {mToast.setText(text);} else {mToast = Toast.makeText(context, text, Toast.LENGTH_SHORT);}mhandler.postDelayed(r, 5000);mToast.show();}public static void showToast(Context context, int strId, int duration) {showToast(context, context.getString(strId), duration);}}
這樣就可以解決一直彈toast訊息的問題了