繁体   English   中英

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

[英]Would this be the correct way to access an arraylist from a Fragment?

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

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
}

我建议使用bundle,seListAdapter运行时错误来查看从段到另一个片段的Pass ArrayList(扩展ListFragment)

这包括

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

那会很好。 除了作为警告。 在创建活动之前,可能会调用此方法。 如果你看一下你会看到的片段生命周期。

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

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数组大小。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM