@@ -15,7 +15,13 @@ import com.haoge.easyandroid.cache.SingleCache
1515 *
1616 * AUTHOR: haoge
1717 */
18- class EasyToast private constructor(private val toast : Toast , private val tv : TextView ? , private val isDefault : Boolean ) {
18+ class EasyToast private constructor(private val layoutId : Int = -1 ,
19+ private val tvId : Int = -1 ,
20+ private val duration : Int = Toast .LENGTH_SHORT ,
21+ private val isDefault : Boolean = true ) {
22+
23+ var toast: Toast ? = null
24+ var tv: TextView ? = null
1925
2026 fun show (resId : Int ) {
2127 show(SingleCache .getApplicationContext().getString(resId))
@@ -39,12 +45,27 @@ class EasyToast private constructor(private val toast: Toast, private val tv: Te
3945 }
4046
4147 private fun showInternal (message : String ) {
48+ createToastIfNeeded()
49+
4250 if (isDefault) {
43- toast.setText(message)
44- toast.show()
51+ toast? .setText(message)
52+ toast? .show()
4553 } else {
4654 tv?.text = message
47- toast.show()
55+ toast?.show()
56+ }
57+ }
58+
59+ @SuppressLint(" ShowToast" )
60+ private fun createToastIfNeeded () {
61+ if (toast == null ) {
62+ if (isDefault) {
63+ toast = Toast .makeText(SingleCache .getApplicationContext(), " " , Toast .LENGTH_SHORT )
64+ } else {
65+ val container = LayoutInflater .from(SingleCache .getApplicationContext()).inflate(layoutId, null )
66+ tv = container.findViewById(tvId)
67+ toast = Toast (SingleCache .getApplicationContext())
68+ }
4869 }
4970 }
5071
@@ -55,28 +76,11 @@ class EasyToast private constructor(private val toast: Toast, private val tv: Te
5576 val DEFAULT : EasyToast by lazy { default() }
5677
5778 private fun default (): EasyToast {
58- checkThread()
59- @SuppressLint(" ShowToast" )
60- val toast = Toast .makeText(SingleCache .getApplicationContext(), " " , Toast .LENGTH_SHORT )
61- return EasyToast (toast, null , true )
79+ return EasyToast (isDefault = true )
6280 }
6381
6482 fun create (layoutId : Int , tvId : Int , duration : Int ): EasyToast {
65- checkThread()
66- val container = LayoutInflater .from(SingleCache .getApplicationContext()).inflate(layoutId, null )
67- val tv: TextView = container.findViewById(tvId)
68- val toast = Toast (SingleCache .getApplicationContext())
69- toast.view = container
70- toast.duration = duration
71- return EasyToast (toast, tv, false )
72- }
73-
74- // Toast限制:在执行了Looper.prepare()的线程中才能创建Toast实例
75- // 这里加强限制,仅限主线程创建
76- private fun checkThread () {
77- if (Looper .myLooper() != Looper .getMainLooper()) {
78- throw RuntimeException (" the toast-create method must called on main-thread" )
79- }
83+ return EasyToast (layoutId, tvId, duration, false )
8084 }
8185 }
8286}
0 commit comments