refactor: 重构 ToastUtils

This commit is contained in:
Quyunshuo
2023-09-23 23:07:14 +08:00
parent e07c98e0a0
commit df93eeec3f
4 changed files with 54 additions and 1042 deletions

View File

@ -0,0 +1,8 @@
package com.quyunshuo.androidbaseframemvvm.base.utils
import androidx.annotation.StringRes
import com.quyunshuo.androidbaseframemvvm.base.BaseApplication.Companion.application as app
fun getString(@StringRes stringRes: Int): String {
return app.getString(stringRes)
}

View File

@ -0,0 +1,46 @@
package com.quyunshuo.androidbaseframemvvm.base.utils
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.widget.Toast
import androidx.annotation.StringRes
import com.quyunshuo.androidbaseframemvvm.base.BaseApplication
private val mToastHandler by lazy { Handler(Looper.getMainLooper()) }
private var mToast: Toast? = null
@JvmOverloads
fun toast(text: String, duration: Int = Toast.LENGTH_SHORT) {
postToast(text, duration)
}
@JvmOverloads
fun toast(@StringRes id: Int, duration: Int = Toast.LENGTH_SHORT) {
postToast(getString(id), duration)
}
private fun postToast(text: String, duration: Int) {
mToastHandler.post {
setToast(text, duration)
mToast?.show()
}
}
private fun setToast(text: String, duration: Int) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
if (mToast == null) {
mToast = Toast.makeText(BaseApplication.context, text, duration)
} else {
mToast?.duration = duration
mToast?.setText(text)
}
} else {
if (mToast != null) {
mToast?.cancel()
mToast = null
}
mToast = Toast.makeText(BaseApplication.context, text, duration)
}
}

View File

@ -1,7 +1,6 @@
package com.quyunshuo.androidbaseframemvvm.base.utils
import android.util.Log
import android.widget.Toast
import com.alibaba.android.arouter.launcher.ARouter
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
@ -41,23 +40,4 @@ fun sendEvent(event: Any) = EventBusUtils.postEvent(event)
*/
fun aRouterJump(routerUrl: String) {
ARouter.getInstance().build(routerUrl).navigation()
}
/**************************************************************************************************/
/**
* toast
* @param msg String 文案
* @param duration Int 时间
*/
fun toast(msg: String, duration: Int = Toast.LENGTH_SHORT) {
ToastUtils.showToast(msg, duration)
}
/**
* toast
* @param msgId Int String资源ID
* @param duration Int 时间
*/
fun toast(msgId: Int, duration: Int = Toast.LENGTH_SHORT) {
ToastUtils.showToast(msgId, duration)
}