显示全局的Toast 防止toast重复弹出

public class ToastUtil {
    private Toast mToast = null;
    private Context mCtx;
    private static ToastUtil mToastUtil = null;

    public ToastUtil(Context ctx){
        mCtx = ctx;
    }

    public static ToastUtil getInstance(Context ctx){
        if(mToastUtil == null)
            mToastUtil = new ToastUtil(ctx);
        return mToastUtil;
    }

    public void showToast(String text,int duration) {  
        if(mToast == null) { 
            mToast = makeText(mCtx, text, duration); 
        } else {
          ((TextView)mToast.getView().findViewById(R.id.TextViewInfo)).setText(text);    
        }  
        mToast.show();
    }  

    public void cancelToast() {  
        if (mToast != null) {  
            mToast.cancel();  
        }  
    }

    public Toast makeText(Context context, String msg,int duration){
        View toastRoot = ((LayoutInflater) context.getSystemService("layout_inflater")).inflate(R.layout.my_toast, null);
        Toast toast=new Toast(context);
        toast.setView(toastRoot);
        TextView tv=(TextView)toastRoot.findViewById(R.id.TextViewInfo);
        tv.getBackground().setAlpha(100);
        tv.setText(msg);
        toast.setDuration(duration);
        return toast;
    }

xml文件:


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
     >

    <TextView
        android:id="@+id/TextViewInfo"
        style="@style/text_Title_style"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:layout_gravity="center" 
        android:textColor="#FFF"
        android:background="#000"/>

LinearLayout>

你可能感兴趣的:(android基础,工具类)