ToastUtil.java 1.51 KB
package com.cnlive.gundam.user.util;

import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.cnlive.gundam.R;


/**
 * Created by xiansong on 2016/12/12.
 */

public class ToastUtil {
    private static long showTime;
    private static String show_msg = "";
    private static Toast current_toast;
    private static final int TOAST_LAYOUT_ID = R.layout.test_layout_toast;

    public static void hideToast() {
        if (current_toast != null) current_toast.cancel();
    }

    public static Toast show(Context context, String msg) {
        if (null == context || TextUtils.isEmpty(msg))
            return null;
        if (showTime + 2000 < System.currentTimeMillis() || !show_msg.equals(msg)) {
            hideToast();

            View view = LayoutInflater.from(context).inflate(TOAST_LAYOUT_ID, null, false);

            ImageView imageView = view.findViewById(R.id.image);
            imageView.setVisibility(View.GONE);

            TextView textView = view.findViewById(R.id.text);
            textView.setText(msg);

            Toast toast = new Toast(context);
            toast.setDuration(Toast.LENGTH_SHORT);
            toast.setView(view);
            toast.show();

            show_msg = msg;
            current_toast = toast;
            showTime = System.currentTimeMillis();
            return toast;
        } else return null;
    }

}