public class ChangeInactiveToastUtil {
public static Toast myToast;
private boolean canceled = true;
private Handler handler = new Handler();
;
private TimeCount timeCount;
private Context context;
private ViewGroup root;
private int str;
private int time;
public ChangeInactiveToastUtil(Context context, ViewGroup root, int str, int time) {
this.context = context;
this.root = root;
this.str = str;
this.time = time;
}
public static Toast getToast(Context context, ViewGroup root, int str) {
Toast toast = new Toast(context);
View view = LayoutInflater.from(context).inflate(R.layout.toast_change_inactive, root);
TextView text = view.findViewById(R.id.textToast);
text.setText(str);
toast.setGravity(Gravity.BOTTOM, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(view);
return toast;
}
public void show() {
timeCount = new TimeCount(time, 1000);
if (canceled) {
timeCount.start();
canceled = false;
showUntilCancel();
}
}
/**
* 隐藏Toast
*/
public void hide() {
if (myToast != null) {
myToast.cancel();
}
if (timeCount != null) {
timeCount.cancel();
}
canceled = true;
}
private void showUntilCancel() {
if (canceled) { //如果已经取消显示,就直接return
return;
}
myToast = ChangeInactiveToastUtil.getToast(context, root, str);
myToast.setGravity(Gravity.BOTTOM, 0, 0);
myToast.show();
handler.postDelayed(new Runnable() {
@Override
public void run() {
showUntilCancel();
}
}, 3500);
}
/**
* 计时器
*/
class TimeCount extends CountDownTimer {
public TimeCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval); // 总时长,计时的时间间隔
}
@Override
public void onFinish() { // 计时完毕时触发
hide();
}
@Override
public void onTick(long millisUntilFinished) { // 计时过程显示
}
}
}
调用
if (changeInactiveToastUtil != null) {
changeInactiveToastUtil.hide();
}
changeInactiveToastUtil = new ChangeInactiveToastUtil(mContext, null, R.string.change_inactive, dataStore.getTempTime());
changeInactiveToastUtil.show();