如何使用 public 静态 class 自定义 Toast

How I can have a custom Toast with a public static class

为了控制toast消息的几种情况,我创建了以下内容

public class ExtraUtils {

public static Activity MyActivity;
public static LayoutInflater mInflater;

public static void MyToast(View view,int ToastCase) 
{
    Context context=MyActivity.getApplicationContext();
    mInflater = LayoutInflater.from(context);

    View customToastroot =mInflater.inflate(R.layout.custom_toast, null);
    Toast customtoast=new Toast(context);
    TextView text = (TextView) customToastroot.findViewById(R.id.txtToast);
    // Set the Text to show in TextView
    switch(ToastCase)
    {
        case 1:
            text.setText("You cannot Select this Again");
            break;
        case 2:
            text.setText("Oops Something went wrong");
            break;
    }
}
}

我称它为 ExtraUtils.MyToast(view,1) 但我在

处得到一个空异常
Context context=MyActivity.getApplicationContext();

改变

Context context = MyActivity.getApplicationContext();

Context context = MyActivity.this;

编辑

抱歉,我以为您是在 MyActivity 本身中编写代码。你需要做的是,

public static void MyToast(View view,int ToastCase, Context context)

并在您调用它的地方的 MyActivity 中,

 ExtraUtils.MyToast(view, 1, MyActivity.this)

您的代码将无法运行!!! MyActivity初始化 ...

发送参数里面的内容

public static void MyToast(Content context,View view,int ToastCase) {
    // Context context=MyActivity.getApplicationContext();
    mInflater = LayoutInflater.from(context);
    View customToastroot =mInflater.inflate(R.layout.custom_toast, null);
    Toast customtoast=new Toast(context);
    TextView text = (TextView) customToastroot.findViewById(R.id.txtToast);
    // Set the Text to show in TextView
    switch(ToastCase) {
        case 1:
            text.setText("You cannot Select this Again");
            break;
        case 2:
            text.setText("Oops Something went wrong");
            break;
    }
   //...Write Code for display toast
}