package com.xw.common.utils import android.annotation.SuppressLint import android.content.Context import android.os.Handler import android.os.Looper import com.xw.common.utils.LogUtils import android.view.Gravity import android.view.View import android.widget.Toast import androidx.appcompat.widget.AppCompatTextView import com.xw.common.R @SuppressLint("SoonBlockedPrivateApi") class ToastUtilCommon(var context: Context) { var toast: Toast? = null var msg: String? = null @SuppressLint("UseCompatLoadingForDrawables") fun create(duration: Int, id: Int?): Toast { if (toast == null) { toast = Toast(context) val contentView = View.inflate(context, R.layout.dialog_toast, null) toast!!.view = contentView toast!!.setGravity(Gravity.CENTER, 0, 0) } val tvMsg = toast!!.view!!.findViewById(R.id.tv_toast_msg) toast!!.duration = duration tvMsg.text = msg val drawableImg = id?.let { context.resources.getDrawable(id, context.theme) } drawableImg?.setBounds(0, 0, drawableImg.minimumWidth, drawableImg.minimumHeight) tvMsg.setCompoundDrawables(drawableImg, null, null, null) return toast!! } companion object { @SuppressLint("StaticFieldLeak") var td: ToastUtilCommon? = null @JvmStatic fun show(msg: String?, duration: Int = Toast.LENGTH_SHORT, drawableId: Int? = null) { msg?.let { if (msg.isNotEmpty()) { if (msg == "Job was cancelled") { return } val tips = if (msg.startsWith("failed to connect to")) { "无法连接服务器" } else { msg } try { Handler(Looper.getMainLooper()).post { if (td == null) { td = ToastUtilCommon(AppGlobals.getApplication()) } td!!.msg = tips val t = td!!.create(duration, drawableId) t.show() } } catch (e: Exception) { if (Looper.myLooper() == null) { Looper.prepare() if (td == null) { td = ToastUtilCommon(AppGlobals.getApplication()) } td!!.msg = tips val t = td!!.create(duration, drawableId) t.show() Looper.loop() } } } } } fun showSuc(msg: String?, duration: Int = Toast.LENGTH_SHORT) { show(msg, duration, R.drawable.svg_toast_suc) } fun showError(msg: String?, duration: Int = Toast.LENGTH_SHORT) { show(msg, duration, R.drawable.svg_toast_error) } fun showWarn(msg: String?, duration: Int = Toast.LENGTH_SHORT){ show(msg, duration, R.drawable.svg_toast_warn) } } }