由于源码中的toast的持续时间为短toast2000,因此判断时间间隔大于2000则新new一个toast进行提示,否则如果toast消失了在进行setText()和show(),就显示不出toast了。
完整代码如下:
class ToastUtil {
companion object {
private var oldMsg: String? = null
private var oneTime: Long = 0
private var twoTime: Long = 0
open fun showText(text: String) {
if (text.isNullOrEmpty()) {
return
}
if (oldMsg.isNullOrEmpty()) {
// 没有弹出过toast
Toast.makeText(BaseComponentApplication.sInstance, text, Toast.LENGTH_SHORT).show()
oldMsg = text
oneTime = System.currentTimeMillis()
} else {
twoTime = System.currentTimeMillis()
if (twoTime - oneTime > 2000) {
// 判断toast上一次显示的时间和这次的显示时间如果大于2000
Toast.makeText(BaseComponentApplication.sInstance, text, Toast.LENGTH_SHORT)
.show()
oneTime = twoTime
oldMsg = text
} else {
// 小余2000
if (!oldMsg.equals(text)) {
// 两次提示内容不一致,则提示
Toast.makeText(BaseComponentApplication.sInstance, text, Toast.LENGTH_SHORT)
.show()
oneTime = twoTime
}
}
}
}
open fun showText(stringsId: Int) {
if (BaseComponentApplication.sInstance.getString(stringsId).isNullOrEmpty()) {
return
}
if (oldMsg.isNullOrEmpty()) {
// 没有弹出过toast
Toast.makeText(BaseComponentApplication.sInstance, BaseComponentApplication.sInstance.getString(stringsId), Toast.LENGTH_SHORT).show()
oldMsg = BaseComponentApplication.sInstance.getString(stringsId)
oneTime = System.currentTimeMillis()
} else {
twoTime = System.currentTimeMillis()
if (twoTime - oneTime > 2000) {
// 判断toast上一次显示的时间和这次的显示时间如果大于2000
Toast.makeText(
BaseComponentApplication.sInstance,
BaseComponentApplication.sInstance.getString(stringsId),
Toast.LENGTH_SHORT
).show()
oneTime = twoTime
oldMsg = BaseComponentApplication.sInstance.getString(stringsId)
} else {
// 小余2000
if (!oldMsg.equals(BaseComponentApplication.sInstance.getString(stringsId))) {
// 两次提示内容不一致,则提示
Toast.makeText(
BaseComponentApplication.sInstance,
BaseComponentApplication.sInstance.getString(stringsId),
Toast.LENGTH_SHORT
).show()
oneTime = twoTime
}
}
}
}
}
}