22
33package io.goooler.demoapp.base.util
44
5- import android.annotation.SuppressLint
65import android.content.Context
76import android.os.Handler
87import android.os.Looper
98import android.widget.Toast
109import androidx.annotation.AnyThread
1110import androidx.annotation.StringRes
1211import androidx.annotation.UiThread
13- import androidx.annotation.WorkerThread
1412import java.lang.ref.WeakReference
1513
16- @SuppressLint(" WrongThread" , " ShowToast" )
1714object ToastUtil {
1815
1916 private val handler = Handler (Looper .getMainLooper())
@@ -32,39 +29,28 @@ object ToastUtil {
3229 @AnyThread
3330 fun show (context : Context , text : String ) {
3431 if (Looper .getMainLooper().thread == = Thread .currentThread()) {
35- showInMainThread (context, text)
32+ showInMain (context, text)
3633 } else {
37- showInWorkerThread (context, text)
34+ handler.post { showInMain (context, text) }
3835 }
3936 }
4037
41- @WorkerThread
42- fun showInWorkerThread (context : Context , @StringRes strResId : Int ) {
43- showInWorkerThread(context, context.getString(strResId))
44- }
45-
46- @WorkerThread
47- fun showInWorkerThread (context : Context , text : String ) {
48- handler.post { showInMainThread(context, text) }
49- }
50-
5138 @UiThread
52- fun showInMainThread (context : Context , @StringRes strResId : Int ) {
53- showInMainThread (context, context.getString(strResId))
39+ fun showInMain (context : Context , @StringRes strResId : Int ) {
40+ showInMain (context, context.getString(strResId))
5441 }
5542
5643 /* *
5744 * 只在主线程调用,真正实现 toast 的方法
5845 */
5946 @UiThread
6047 @Synchronized
61- fun showInMainThread (context : Context , text : String ) {
48+ fun showInMain (context : Context , text : String ) {
6249 // 把上一条先置空,再显示下一条
6350 toast?.get()?.cancel()
6451 toast = null
6552 Toast .makeText(context, text, Toast .LENGTH_SHORT ).also {
66- it.show()
6753 toast = WeakReference (it)
68- }
54+ }.show()
6955 }
7056}
0 commit comments