我定义了自己的显示Toast的方法,我想从另一个Activity中调用它。当我这样做时,我的应用程序崩溃了。你有一些Attempt to invoke virtual method.... on a null object reference吗?

吐司方法:

 public void showToastDown(Context context, String message) {
    context = getApplicationContext();

    inflater = getLayoutInflater();
    View v = inflater.inflate(R.layout.toast_down, (ViewGroup) findViewById(R.id.toast_down_root));

    TextView tvToastDown = v.findViewById(R.id.tvToastDown);
    tvToastDown.setText(message);
    Toast toast = new Toast(context);
    toast.setGravity(Gravity.BOTTOM|Gravity.FILL_HORIZONTAL, 0,0);
    toast.setDuration(Toast.LENGTH_SHORT);
    toast.setView(v);
    toast.show();

}


以及第二活动的代码:

  switch (item.getItemId()){
    case  R.id.btnAddActionBar:

        MainActivity mainActivity= new MainActivity();
        mainActivity.showToastDown(this, "TEXT");
        break;
}
    return super.onOptionsItemSelected(item);
}

最佳答案

从代码中删除此行,因为您已经在传递上下文的值,因此无需再次使用Application Context进行初始化。

context = getApplicationContext();


编辑:像这样更改您的方法:

public void showToastDown(Context context, String message) {
    LayoutInflater inflater = ((Activity)context).getLayoutInflater();
    View v = inflater.inflate(R.layout.toast_down, (ViewGroup) ((Activity)context).findViewById(R.id.toast_down_root));

    TextView tvToastDown = v.findViewById(R.id.tvToastDown);
    tvToastDown.setText(message);
    Toast toast = new Toast(context);
    toast.setGravity(Gravity.BOTTOM|Gravity.FILL_HORIZONTAL, 0,0);
    toast.setDuration(Toast.LENGTH_SHORT);
    toast.setView(v);
    toast.show();
}

10-05 23:26