取消上一个Android Toast时不显示

时间:2019-02-09 23:50:36

标签: android android-context toast applicationcontext android-toast

我有一个MostRecent id Date1 Date2 Date3 2003-01-01 1 2001-01-01 2002-01-01 2003-01-01 2003-01-01 2 2001-01-01 2003-01-01 2002-01-01 2003-01-01 3 2002-01-01 2001-01-01 2002-01-01 2003-01-01 4 2002-01-01 2003-01-01 2001-01-01 2003-01-01 5 2003-01-01 2001-01-01 2002-01-01 2003-01-01 6 2003-01-01 2002-01-01 2001-01-01 2003-01-01 11 NULL 2002-01-01 2003-01-01 2003-01-01 12 NULL 2003-01-01 2002-01-01 2003-01-01 13 2003-01-01 NULL 2002-01-01 2003-01-01 14 2002-01-01 NULL 2003-01-01 2003-01-01 15 2003-01-01 2002-01-01 NULL 2003-01-01 16 2002-01-01 2003-01-01 NULL 2003-01-01 21 2003-01-01 NULL NULL 2003-01-01 22 NULL 2003-01-01 NULL 2003-01-01 23 NULL NULL 2003-01-01 NULL 31 NULL NULL NULL 单例,它显示了一个吐司,如果已经显示在屏幕上,它会取消上一个吐司。这是我当前的代码:

ToastUtil

但是Toast消息没有显示在电话上。 object ToastUtil { private lateinit var mToast: Toast fun init(applicationContext: Context) { mToast = Toast.makeText(applicationContext, null, Toast.LENGTH_SHORT) } fun showShortToast(message: String) { mToast.cancel() mToast.setText(message) mToast.duration = Toast.LENGTH_SHORT mToast.show() } fun showShortToast(messageId: Int) { mToast.cancel() mToast.setText(messageId) mToast.duration = Toast.LENGTH_SHORT mToast.show() } } 肯定已经在我的自定义ToastUtil实现中初始化(init(applicationContext):

App

我尝试https://stackoverflow.com/a/33878500/8434188无济于事。我有什么想念的吗?

1 个答案:

答案 0 :(得分:0)

此代码现已正常运行,并且正在显示Toasts。它也更清洁 ,因为我不必在应用实现中对其进行初始化。

object ToastUtil {

    private var mToast: Toast? = null

    fun Context.showShortToast(message: String) {
        if (mToast != null) {
            mToast!!.cancel()
        }
        mToast = Toast.makeText(this, message, Toast.LENGTH_SHORT)
        mToast?.show()
    }

    fun Context.showShortToast(
        messageId: Int,
        vararg strings: String = arrayOf()
    ) {
        this.showShortToast(getString(messageId, strings))
    }
}