防止Toast N次,Toast一直不消失.
完整代码:
import android.widget.Toast;
public class Tools {
private static Toast mToast;
private static Handler mHandler = new Handler();
private static Runnable r = new Runnable() {
public void run() {
mToast.cancel();
}
};
//调用showToast提示
public static void showToast(Context mContext, String text) {
try {
//每次调用先把前一个提示给remove掉
mHandler.removeCallbacks(r);
if (mToast != null) {
mToast.setText(text);
} else {
mToast = Toast.makeText(mContext, text, Toast.LENGTH_SHORT);
}
mHandler.postDelayed(r, 2000);
mToast.show();
} catch (Resources.NotFoundException e) {
e.printStackTrace();
}
}
public static void showToast(Context mContext, int resId) {
showToast(mContext, mContext.getResources().getString(resId));
}
}