【问题标题】:Would this be the correct way to access an arraylist from a Fragment?这是从片段访问数组列表的正确方法吗?
【发布时间】:2016-08-06 19:39:13
【问题描述】:

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

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。
  • 它是在哪里创建的?你可以从主机 Activity 中获取它吗?
  • 我可以通过意图传递对象数组,但我认为传递索引要容易得多,因为一旦有了索引,我就可以从下一个活动中访问该数组。
  • 这可能不是最好的方法,但这完全可以。如果它说你的数组大小是 0,那么如果你发布了其余的代码,那么它真的为零。请注意,如果这是错误的方法,它会说它是 null 并崩溃。

标签: android android-fragments arraylist oncreate


【解决方案1】:

这样就可以了。除非作为警告。这很可能在您的活动创建之前被调用。如果您查看片段生命周期,您会看到。

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

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。

【讨论】:

    【解决方案2】:

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

    这包括

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-10
      • 2011-08-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多