Skip to content
This repository was archived by the owner on Jul 16, 2024. It is now read-only.

Commit e9dde09

Browse files
committed
ToastUtil 优化
1 parent 724dc61 commit e9dde09

File tree

1 file changed

+6
-20
lines changed
  • base/src/main/kotlin/io/goooler/demoapp/base/util

1 file changed

+6
-20
lines changed

base/src/main/kotlin/io/goooler/demoapp/base/util/ToastUtil.kt

Lines changed: 6 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,15 @@
22

33
package io.goooler.demoapp.base.util
44

5-
import android.annotation.SuppressLint
65
import android.content.Context
76
import android.os.Handler
87
import android.os.Looper
98
import android.widget.Toast
109
import androidx.annotation.AnyThread
1110
import androidx.annotation.StringRes
1211
import androidx.annotation.UiThread
13-
import androidx.annotation.WorkerThread
1412
import java.lang.ref.WeakReference
1513

16-
@SuppressLint("WrongThread", "ShowToast")
1714
object 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

Comments
 (0)