ToastHelper.kt 1.32 KB
Newer Older
严久程 committed
1
package com.yidianling.ydl_pay.toast
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49

import android.content.Context
import android.support.annotation.StringRes
import android.text.TextUtils
import android.widget.Toast

/**
 * author : Zhangwenchao
 * e-mail : zhangwch@yidianling.com
 * time   : 2018/01/29
 *
 * 提示信息的封装类,使用单例 toast,防止重复弹出提示
 */
class ToastHelper private constructor() {

    private var toast: Toast? = null

    companion object {
        private fun getInstance(): ToastHelper {
            return Holder.INSTANCE
        }

        fun show(context: Context, text: String) {
            getInstance().show(context.applicationContext, text)
        }

        fun show(context: Context, @StringRes resId: Int) {
            getInstance().show(context.applicationContext, resId)
        }
    }

    private fun show(context: Context, text: CharSequence) {
        if (TextUtils.isEmpty(text)) return
        if (toast == null) toast = Toast.makeText(context, text, Toast.LENGTH_SHORT)
        else toast?.setText(text)
        toast?.show()
    }

    private fun show(context: Context, @StringRes resId: Int) {
        if (toast == null) toast = Toast.makeText(context, resId, Toast.LENGTH_SHORT)
        else toast?.setText(resId)
        toast?.show()
    }

    private object Holder {
        val INSTANCE = ToastHelper()
    }
}