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

相關問題