从Fragment中访问ArrayList的正确方法是什么?

3

我只需要知道正确的语法来访问在另一个类中创建的数组。

public class item_fragment extends Fragment {

 ArrayList<MyItems> mylist;

 @Override
 public View onCreateView(  LayoutInflater inflater,
                             ViewGroup container,
                             Bundle savedInstanceState) {



         mylist =   ((MyApplication)  getActivity().getApplication()).getItemsArrayList();

    return inflater.inflate(R.layout.course_work_item_fragment,container, false);
}//ends onCreate View
}

一直告诉我大小为0。 - Carlitos
它是在哪里创建的?你能否从主机Activity中获取它? - John P.
我可以通过意图传递对象数组,但我认为传递索引更容易,因为一旦我有了索引,就可以从我的下一个活动中访问数组。 - Carlitos
这可能不是最好的方法,但完全可行。如果它说你的数组大小为0,很有可能如果你发布了其余的代码,它确实会是零。请注意,如果这是错误的方法,它会说它为空并崩溃。 - Tatarize
2个回答

0

0

这个方案很好。但是需要注意的是,它可能会在你的活动创建之前被调用。如果你查看片段生命周期,你会发现:

将片段带到恢复状态(与用户交互)的核心生命周期方法系列包括:

onAttach(Activity) called once the fragment is associated with its activity.
onCreate(Bundle) called to do initial creation of the fragment.
onCreateView(LayoutInflater, ViewGroup, Bundle) creates and returns the view hierarchy associated with the fragment.
onActivityCreated(Bundle) tells the fragment that its activity has completed its own Activity.onCreate().
onViewStateRestored(Bundle) tells the fragment that all of the saved state of its view hierarchy has been restored.
onStart() makes the fragment visible to the user (based on its containing activity being started).
onResume() makes the fragment begin interacting with the user (based on its containing activity being resumed).

你会注意到,onViewCreated方法可以很容易地早于activity创建。因此,如果你重新初始化了那个数组,你的fragment将拥有一个空数组,没有任何内容加入其中。或者,如果你在onActivityCreated()被调用之前检查数组的大小,假设你在初始化完成后给数组赋值,你仍然会得到一个0数组大小。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接