我如何拥有一个带有公共静态类的自定义Toast

时间:2016-04-05 10:59:57

标签: android toast

我创建了以下内容,以便控制几个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),但我在

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

2 个答案:

答案 0 :(得分:1)

更改

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)

答案 1 :(得分:1)

您的代码无效!!! 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
}