Skip to content

Commit

Permalink
ToastUtil
Browse files Browse the repository at this point in the history
  • Loading branch information
YeChao committed Jan 8, 2021
1 parent 983ce3c commit 35eeb26
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 10 deletions.
16 changes: 13 additions & 3 deletions yutils/src/main/java/com/yechaoa/yutils/ToastUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

public class ToastUtil {

private static Toast toast;
private static Toast toast = null;

/**
* showToast 底部显示(默认) 直接用show()即可
Expand Down Expand Up @@ -61,7 +61,7 @@ public void run() {
*/
private static void createToast(String msg) {
if (toast == null) {
toast = Toast.makeText(YUtils.getApp(), msg, Toast.LENGTH_SHORT);
toast = Toast.makeText(YUtils.getApp().getApplicationContext(), msg, Toast.LENGTH_SHORT);
} else {
toast.setText(msg);
}
Expand Down Expand Up @@ -115,7 +115,7 @@ public void run() {
*/
private static void createCenterToast(String msg) {
if (toast == null) {
toast = Toast.makeText(YUtils.getApp(), msg, Toast.LENGTH_SHORT);
toast = Toast.makeText(YUtils.getApp().getApplicationContext(), msg, Toast.LENGTH_SHORT);
} else {
toast.setText(msg);
}
Expand Down Expand Up @@ -149,4 +149,14 @@ public static void cancel() {
}
}

/**
* 回收Toast
*/
public static void release() {
if (toast != null) {
toast.cancel();
toast = null;
}
}

}
25 changes: 18 additions & 7 deletions yutilskt/src/main/java/com/yechaoa/yutilskt/ToastUtil.kt
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ object ToastUtil {
*/
private fun createToast(msg: String) {
if (toast == null) {
toast = Toast.makeText(YUtils.getApp(), msg, Toast.LENGTH_SHORT)
toast = Toast.makeText(YUtils.getApp().applicationContext, msg, Toast.LENGTH_SHORT)
} else {
toast!!.setText(msg)
}
Expand Down Expand Up @@ -83,7 +83,7 @@ object ToastUtil {
*/
private fun createCenterToast(msg: String) {
if (toast == null) {
toast = Toast.makeText(YUtils.getApplication(), msg, Toast.LENGTH_SHORT)
toast = Toast.makeText(YUtils.getApp().applicationContext, msg, Toast.LENGTH_SHORT)
} else {
toast!!.setText(msg)
}
Expand All @@ -101,14 +101,25 @@ object ToastUtil {
*/
@Deprecated("简化调用,使用cancel()即可", ReplaceWith("ToastUtilKt.cancel()"))
fun cancelToast() {
if (toast != null) {
toast!!.cancel()
}
toast?.cancel()
}

/**
* 取消Toast
* onDestroy时调用,或者onPause
* 当前页面finish之后在下一个页面不会显示
*/
fun cancel() {
if (toast != null) {
toast!!.cancel()
toast?.cancel()
}

/**
* 回收Toast
*/
fun release() {
toast?.let {
it.cancel()
toast = null
}
}
}

0 comments on commit 35eeb26

Please sign in to comment.