且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么我的Fragment中的上下文为null?

更新时间:2023-02-25 20:36:31

您正试图获得上下文首次实例化 Fragment 时。那时,它没有附加到活动,因此没有有效的上下文

You're attempting to get a Context when the Fragment is first instantiated. At that time, it is NOT attached to an Activity, so there is no valid Context.

查看片段生命周期 onAttach() onDetach()之间的所有内容都包含对有效Context实例的引用。此Context实例通常通过 getActivity()

Have a look at the Fragment Lifecycle. Everything between onAttach() to onDetach() contain a reference to a valid Context instance. This Context instance is usually retrieved via getActivity()

检索代码示例:

private Helper mHelper;

@Override
public void onAttach(Activity activity){
   super.onAttach (activity);
   mHelper = new Helper (activity);
}

我用 onAttach()在我的例子中,@ LaurenceDawson使用 onActivityCreated()。注意差异。由于 onAttach()已经传递给它的活动,我没有使用 getActivity ()。相反,我使用了传递的参数。对于生命周期中的所有其他方法,您必须使用 getActivity()

I used onAttach() in my example, @LaurenceDawson used onActivityCreated(). Note the differences. Since onAttach() gets an Activity passed to it already, I didn't use getActivity(). Instead I used the argument passed. For all other methods in the lifecycle, you will have to use getActivity().