我想显示祝酒词。如果我在oncreate()中这样做,它会工作得很好。但我想这样做,我得到一个错误:
java.lang.NullPointerException:尝试调用虚拟方法
'android.content.res.resources android.content.context.getresources()'
在空对象引用上
我该怎么办?
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!");
}
}
最佳答案
触发Java.Lang.NullPointerException
是因为您正在手动创建和使用MainActivity
的实例。
不要使用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?