编程语言
首页 > 编程语言> > Xamarin Toast消息错误(C#)

Xamarin Toast消息错误(C#)

作者:互联网

我想显示一个Toast Message.如果我在onCreate()中执行此操作,它可以正常工作.但我想这样做,我得到一个错误:

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

我该怎么办?

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!"); 
    }
}

解决方法:

由于您手动创建和使用MainActivity实例,因此会触发Java.Lang.NullPointerException.

而不是使用MainActivity的自定义实例在Click中显示Toast消息,而是简化代码以使用片段现有活动参考:

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!"); 
    }
}

此代码假定拥有活动始终是MainActivity的实例.

看到:

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

标签:android,c-2,xamarin,toast,android-toast
来源: https://codeday.me/bug/20190727/1555531.html