我开发了一个有 15 个屏幕的应用程序。现在我想在所有这 15 个屏幕中显示自定义 toast 消息。为此,我夸大了一种布局。但它只能在一个屏幕上工作。因此,我编写了一个方法来Toast
在所有屏幕上显示自定义。每当我想显示 toast 消息时,我都会调用该方法。但我得到了java.lang.NullPointerException
。如何解决这个问题?以下是我的代码,
public static void showToastMessage(String message){
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast,
(ViewGroup) ((Activity) context).findViewById(R.id.customToast));
// set a message
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText(message);
// Toast...
Toast toast = new Toast(context);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
}
日志是
java.lang.NullPointerException
at com.guayama.utilities.CommonMethods.showToastMessage(CommonMethods.java:474)
at android.view.View.performClick(View.java:3511)
at android.view.View$PerformClick.run(View.java:14105)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)