getActivity() 什么时候可以 return null?
when getActivity() can return null?
也许是个愚蠢的问题,但是当 getActivity()
可以返回 null 时,是否可以将 getActivity()
保存到 onViewCreated
中的字段,例如 mActivity
并在任何地方使用它?
第一个例子,fragment 中的 onStop 方法。可以吗,还是我永远不应该那样检查?:
@Override
public void onStop() {
registrationMessage(RequestService.MSG_UNREGISTER);
if (getActivity() != null)
getActivity().unbindService(serviceConnection);
super.onStop();
}
确保 onStop 中的上下文不为 null 就可以了,
这是来自 developers documentation -
的警示线
if you need a Context object within your Fragment, you can call
getActivity(). However, be careful to call getActivity() only when the
fragment is attached to an activity. When the fragment is not yet
attached, or was detached during the end of its lifecycle,
getActivity() will return null.
也许是个愚蠢的问题,但是当 getActivity()
可以返回 null 时,是否可以将 getActivity()
保存到 onViewCreated
中的字段,例如 mActivity
并在任何地方使用它?
第一个例子,fragment 中的 onStop 方法。可以吗,还是我永远不应该那样检查?:
@Override
public void onStop() {
registrationMessage(RequestService.MSG_UNREGISTER);
if (getActivity() != null)
getActivity().unbindService(serviceConnection);
super.onStop();
}
确保 onStop 中的上下文不为 null 就可以了, 这是来自 developers documentation -
的警示线if you need a Context object within your Fragment, you can call getActivity(). However, be careful to call getActivity() only when the fragment is attached to an activity. When the fragment is not yet attached, or was detached during the end of its lifecycle, getActivity() will return null.