这是从片段访问arraylist的正确方法吗?

时间:2016-04-15 01:36:51

标签: android android-fragments arraylist oncreate

只需要知道访问在不同类中创建的数组的正确语法。

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
}

2 个答案:

答案 0 :(得分:0)

我建议您查看Pass ArrayList from fragment to another fragment(extends ListFragment) using bundle, seListAdapter runtime error

这包括

  

如果仔细阅读代码,有一件事是你在Monday_fragment中声明了ArrayAdapter,所以每次将这个片段替换为其他片段时,这个列表都会初始化。所以只需在MainActivity中创建一个ArrayAdapter,然后在相同的setter中创建一个ArrayAdapter,并在Monday_fragment中更改你的方法ArrayList toStringList(Collection entryLogs),如下所示

答案 1 :(得分: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可以轻松地在创建的活动之前。因此,如果您说重新初始化该数组,您的片段将有一个空数组,从未添加任何内容。或者,如果在调用onActivityCreated()之前检查了大小,则假设在初始化之后给出数组值,则仍然会有0数组大小。