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

import android.content.Context;
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;

import org.jivesoftware.smack.util.StringUtils;


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

public class ToastUtil {
    private static Toast toast;

    private static long back_pressed;
    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 (!ShockwaveApplication.appOnline)
//            return;
        hide();
        if (null == context || StringUtils.isEmpty(msg))
            return null;
        if (back_pressed + 2000 < System.currentTimeMillis() || !show_msg.equals(msg)) {
            hideToast();
            show_msg = msg;
            toast = new Toast(context);
            View view = LayoutInflater.from(context).inflate(TOAST_LAYOUT_ID, null, false);
            ImageView imageView = (ImageView) view.findViewById(R.id.image);
            TextView textView = (TextView) view.findViewById(R.id.text);
            imageView.setVisibility(View.GONE);

            textView.setText(msg);
            toast.setDuration(Toast.LENGTH_SHORT);
            toast.setView(view);
            toast.show();
            current_toast = toast;
        }
        back_pressed = System.currentTimeMillis();
        return toast;
    }

    public static boolean checkNetwork(Context context) {
        if (context == null) return false;
        if (NetworkUtil.isConnectInternet(context.getApplicationContext())) {
            return true;
        } else {
            show(context.getApplicationContext(), context.getString(R.string.net_connect_toast));
            return false;
        }
    }

    public static void showToast(Context context, String text) {
        show(context,text);
    }

    public static void hide() {
        if (toast != null) toast.cancel();
    }
}