1 - 从片段中获取数组的大小:
在这种情况下,您需要获取添加片段的实例,并从它的全局变量中检索您需要的值。
在片段中:
public List<MyObject> myList;
活动中:
int size;
MyFragment fragment = (MyFragment)getSupportFragmentManager().findFragmentByTag("myFragmentTag");
if(fragment != null && is fragment.isAdded())
size = fragment.myList.size();
PS:在上面的情况下,添加时不要忘记在片段中添加标签
2 - 将数组传递给片段:
在这种情况下,您需要使 Object Serializable,将其作为参数添加到即将添加的 Fragment 中,然后在添加 Fragment 时,在 Fragment 内检索先前添加的 Object
使对象可序列化并将其添加到 Activity 的参数中
活动中:
public MySerializableObjectList myList;
将数组添加到Activity中的fragment:
MyFragment myFragment = new MyFragment();
fragmentManager = getSupportFragmentManager();
Bundle bundle = new Bundle();
bundle.putSerializable("myArrayTag", myList);
myFragment.setArguments(bundle);
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragment_container, myFragment,"myFragmentTag").commit();
在片段中:
public MySerializableObjectList myList;
if(getArguments != null)
myList = (MySerializableObjectList)getArguments().getSerializable("myArrayTag");
List<MySerializableObject> myListObject;
if(myList != null)
myListObject = myList.getMySerializableObjectList();