Android Can';不要制作定制的吐司
我在获取自定义toast类以在任何活动中重用时遇到了同样的问题 无论我如何尝试,都会出现Android Can';不要制作定制的吐司,android,class,nullpointerexception,toast,Android,Class,Nullpointerexception,Toast,我在获取自定义toast类以在任何活动中重用时遇到了同样的问题 无论我如何尝试,都会出现null指针异常或invoke findviewbyid方法错误。请帮忙 class Toaster extends Activity { Toaster(Context context, String message) { { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LA
null指针异常
或invoke findviewbyid方法
错误。请帮忙
class Toaster extends Activity {
Toaster(Context context, String message) {
{
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.toast_layout, (ViewGroup)context.findViewById(R.id.toastroot));
TextView text = (TextView) layout.findViewById(R.id.toasttext);
text.setText(message);
Toast toast = new Toast(context);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();
}
}}
我不明白你为什么要延长活动时间。您从不直接构造活动,因此这里的构造函数是没有意义的。
如果您正在尝试自定义Toast消息,请尝试以下解决方案:
编辑:
更具体地说,您为什么会获得NPE:
View layout = inflater.inflate(R.layout.toast_layout, (ViewGroup)context.findViewById(R.id.toastroot));
您正在将上下文强制转换到视图组,然后使用它在该视图组中查找
R.id.toastroot
。很可能-此处的上下文为空,因此这是异常的来源。这不是在活动中实现此类功能的最佳方式
相反,您可以使用具有静态方法的类来为您执行此操作,如下所示:
public final class Toaster {
public static void showToast(final Context context, String message) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.toast_layout, (ViewGroup)context.findViewById(R.id.toastroot));
TextView text = (TextView) layout.findViewById(R.id.toasttext);
text.setText(message);
Toast toast = new Toast(context);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();
}
}
Toaster.showToast(context,"some message");
然后,你会打这样的电话:
public final class Toaster {
public static void showToast(final Context context, String message) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.toast_layout, (ViewGroup)context.findViewById(R.id.toastroot));
TextView text = (TextView) layout.findViewById(R.id.toasttext);
text.setText(message);
Toast toast = new Toast(context);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();
}
}
Toaster.showToast(context,"some message");
R.id.toast_布局的xml是什么样子的?谢谢!现在非常接近…活动不喜欢传递的上下文,而toaster类不喜欢上下文。findviewbyid…这两个错误相关吗?我猜我得到了错误的上下文。可能吗?抱歉,我不理解Toaster.showtoos(getApplicationcontext(),“一些消息”);是将传递到Toast.showtoos的。我现在的问题是context.findview by id…findview by id有错误删除context.findviewById。你们不需要那个来膨胀你们的观点。等级烤面包机是它自己的外部等级,对吗?不在活动中你绝对是对的。无论出于何种原因,FindByID本身都不起作用。我已经尝试了我能想到的每一种组合。我在这里遗漏了一些东西。目标是能够从我的3项活动中的任何一项中调用toast类,并向其发送不同的消息。