在安卓开发中,如果我们直接使用
Toast.makText(context, text, Toast.LENGTH_SHORT).show()
来显示Toast消息的话,若用户在当前Toast还未结束时继续触发Toast提示,应用只能等当前Toast播放完毕才能播放下一条。如果用户多次点击Toast,那么Toast提示会一直弹出。
ToastUtil
思路:当有新的Toast时,调用当前Toast的cancel()
方法来提前退出,然后生成新的Toast。
Java版本
public class ToastUtil {
private Toast mToast = null;
public static void showToast(Context mContext, String msg) {
if (Toast != null) {
mToast.cancel();
}
mToast = Toast.makeText(mContext, msg, Toast.LENGTH_SHORT);
mToast.show();
}
Kotlin版本
object ToastUtil {
private var mToast: Toast? = null
fun showToast(mContext: Context, msg: String) {
mToast?.cancel()
mToast = Toast.makeText(mContext, msg, Toast.LENGTH_SHORT)
mToast?.show()
}
}
网友评论