我创建了以下内容,以便控制几个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();
答案 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
}