Xamarin Toast Message error (C#)

帅比萌擦擦* 提交于 2019-12-10 19:57:39

问题


I want to display a toast Message. If I'd do this in onCreate() it'd work fine. But I want to do it like this and I get an error:

Java.Lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference

What should I do?

public  void textToast(string textToDisplay) {               
    Toast.MakeText(this,
    textToDisplay, ToastLength.Long).Show();
}
class SampleTabFragment : Fragment
{
    Button add;
    MainActivity main = new MainActivity();
    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        base.OnCreateView(inflater, container, savedInstanceState);
        var view = inflater.Inflate(Resource.Layout.Tab, container, false);     
        add = view.FindViewById<Button>(Resource.Id.add);      
        add.Click += Click;
        return view;
    }
    void Click(object sender, EventArgs eventArgs)
    {      
        main.textToast( "I like Toast!"); 
    }
}

回答1:


The Java.Lang.NullPointerException is triggered because you are manually creating and using an instance of MainActivity.

Instead of using a custom instance of MainActivity to display your toast message in Click, simplify your code to use the fragments existing activity reference:

public  void textToast(string textToDisplay) {               
    Toast.MakeText(this,
    textToDisplay, ToastLength.Long).Show();
}

class SampleTabFragment : Fragment
{
    Button add;

    // Remove manual creation code
    // MainActivity main = new MainActivity();

    // ...

    void Click(object sender, EventArgs eventArgs)
    {      
        (Activity as MainActivity).textToast( "I like Toast!"); 
    }
}

This code assumes that the owning activity is always an instance of MainActivity.

See:

  • Fragment getActivity()
  • How to use the method of an Activity in a DialogFragment?



回答2:


If I understand correctly your question, I think a good solution may be this one:

        public void makeToast(Context ctx, string str)
        {
            Toast.MakeText(ctx, str, ToastLength.Long).Show();
        }

And when you use it in every fragment you have, you can call it just writing:

makeToast(this.Activity, "test!");

Works for me, let me know :)



来源:https://stackoverflow.com/questions/36264801/xamarin-toast-message-error-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!