api
工具类和扩展工具方法名完全一致。
toastShort :吐司短时间
toastLong :吐司长时间
toast :吐司自定义时间
源码
class ToastUtils private constructor() {
private var toast: Toast? = null
companion object {
val instance = ToastSingle.holder
}
private object ToastSingle {
val holder = ToastUtils()
}
fun toastShort(context: Context?, @StringRes text: Int) {
if (context == null) return
toastShort(context, context.getResource().getString(text))
}
fun toastShort(context: Context?, text: CharSequence?) {
toast(context, text, Toast.LENGTH_SHORT)
}
fun toastLong(context: Context?, @StringRes text: Int) {
if (context == null) return
toastShort(context, context.getResource().getString(text))
}
fun toastLong(context: Context?, text: CharSequence?) {
toast(context, text, Toast.LENGTH_LONG)
}
/**
* 通用吐司
*
* @param context
* @param text 吐司文本
* @param duration 持续时间
*/
fun toast(context: Context?, text: CharSequence?, duration: Int) {
if (context == null || text.isNullOrEmpty()) return
if (toast == null) {
toast = Toast.makeText(context, text, duration)
toast?.show()
} else {
toast?.setText(text)
toast?.duration = duration
toast?.show()
}
}
fun cancel() {
toast?.cancel()
}
}