如果父 Activity 包始终具有传递给片段的对象,那么片段包的用途是什么?

What is the purpose of a Fragment bundle if the parent Activity bundle always has the objects that are passed to the Fragment?

我在 Activity 中有一个模型,这个 Activity 中的片段需要访问它。我目前正在通过片段包传递它,但为什么我不能只从片段中的 Activity 访问它?

例如,我会在片段 onCreate():

中使用这段代码

Model model = ((ActivityWithModel) getActivity).getModel();

一般来说,为什么这不能总是Activity和Fragment共享对象的方法,或者Activity给Fragment传递参数的方法?为什么需要 Fragment 包?

因为Fragments可以从多个Activities访问。

使用 getActivity() 使您的 Fragment 依赖于特定的 Activity class。如果您想在几个不相关的活动中重复使用同一个片段,您可能希望避免这种情况。您也可以更轻松地测试您的 Fragment

那么getActivity()不是一直可用的,只有从Fragment的onActivityCreated()开始才可用。有时你想更早地将参数传递给 Fragment 的 onCreate() ,所以你必须为此使用 Bundle