0

我正在使用viewpager并创建片段,并且想要传递数组列表。所以我曾尝试下面的事情:如何将自定义对象数组列表从实例传递到片段

MainActivity:

private ArrayList<customers> mArrayList = null; 

    ViewPagerAdapter adapter = new ViewPagerAdapter(MainActivity.this.getSupportFragmentManager()); 

    adapter.addFrag(NewCustomer.newInstance(mArrayList), "NewCustomer"); 

现在片段类我创建实例:

public static final ArrayList<customers> data = new ArrayList<customers>(); 

public static final NewCustomer newInstance(ArrayList<customers> mArrayList) { 

     NewCustomer f = new NewCustomer(); 
     Bundle bdl = new Bundle(1); 
     bdl.putParcelableArrayList(data, mArrayList); 
     f.setArguments(bdl); 
     return f; 
    } 

但是,这是行不通的。它在bdl.putParcelableArrayList上显示错误我想要获取数组列表并将其存储到该类的本地数组列表中。

如何获取我的自定义对象的数组列表?

回答

1

你可以试试吗?

public static final NewCustomer newInstance(ArrayList<customers> mArrayList) { 

     NewCustomer f = new NewCustomer(); 
     Bundle bdl = new Bundle(1); 
     this.data = mArrayList; // assign its Value 
     bdl.putParcelableArrayList(data, mArrayList); 
     f.setArguments(bdl); 
     return f; 
    } 

this.data = mArrayList将赋值给片段的当前成员变量。现在可以在当前片段中访问它。

+0

你应该解释为什么你提供的代码正在工作,它在做什么。如果您仅提供一个代码,这将不会帮助OP和下列可能最终出现类似问题的用户。 – AxelH

+0

@AxelH,是的,你说得对,我为此道歉。 –

+0

不要道歉;)但你如何解释静态上下文中'this'的用法?我真的没有那个部分。或者该方法的错误用法;) – AxelH

1

请检查您的模型类“NewCustomer”是否实现Parcelable。

4

您传递的第一个参数是错误的。 检查的定义:

putParcelableArrayList(String key, ArrayList<? extends Parcelable> value) 

定义键按照您的片段:

public static final String KEY; 

要获取的ArrayList在你的片段使用本地变量下面的代码:

@Override 
public void onStart() { 
    super.onStart(); 
    Bundle arguments = getArguments(); 
    ArrayList<customers> customer_list = arguments.getParcelable(KEY); 
} 
+0

写得很好。你可以添加[source](https://developer.android.com/reference/android/os/Bundle.html),并展示如何用KEY调用putParcelable(你需要初始化,因为这是一个常量) – AxelH

相关问题