package com.sw.inbound.utils; import android.annotation.SuppressLint; import android.content.Context; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.sw.inbound.MyApp; import com.sw.inbound.R; import java.util.Timer; import java.util.TimerTask; /** * The type Toast utils. */ public class CustomToastUtils { private static Toast toast; @SuppressLint("StaticFieldLeak") private static TextView textCenterView; /** * Show center toast. * * @param text the text */ public static void showToast(String text) { Context context = MyApp.Companion.getInstance(); if (toast == null) { View view = LayoutInflater.from(context).inflate(R.layout.layout_custom_toast, null); textCenterView = view.findViewById(R.id.toast_tv); toast = new Toast(context); toast.setGravity(Gravity.CENTER, 0, 20); toast.setDuration(Toast.LENGTH_SHORT); toast.setView(view); } textCenterView.setText(text); toast.show(); } /** * Show center toast. * * @param text the text */ public static void showToast(String text, int duration) { Context context = MyApp.Companion.getInstance(); if (toast == null) { View view = LayoutInflater.from(context).inflate(R.layout.layout_custom_toast, null); textCenterView = view.findViewById(R.id.toast_tv); toast = new Toast(context); toast.setGravity(Gravity.CENTER, 0, 20); toast.setView(view); } textCenterView.setText(text); toast.setDuration(duration); toast.show(); } public static void showLongToast(String text) { Context context = MyApp.Companion.getInstance(); if (toast == null) { View view = LayoutInflater.from(context).inflate(R.layout.layout_custom_toast, null); textCenterView = view.findViewById(R.id.toast_tv); toast = new Toast(context); toast.setGravity(Gravity.TOP, 0, 20); toast.setDuration(Toast.LENGTH_LONG); toast.setView(view); } textCenterView.setText(text); showMyToast(toast, 1000000 * 30); } //自定义Toast控件 private static void showMyToast(final Toast toast, final int cnt) { final Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { toast.show(); } }, 0, Toast.LENGTH_LONG); new Timer().schedule(new TimerTask() { @Override public void run() { toast.cancel(); timer.cancel(); } }, cnt); } public static void showSystemToast(String text) { Context context = MyApp.Companion.getInstance(); Toast.makeText(context, text, Toast.LENGTH_SHORT).show(); } }