2017-06-12 23 views
-3

我想要做一個當我點擊listview項目,並且該行的數據將傳遞到另一個片段並顯示它。但現在問題是片段已經可以顯示,但數據無法通過。我使用bundle來設置參數。來自列表視圖的數據不能傳遞到片段

我已經找到了職位,但不會有任何帖子幫我解決這個問題..

這是我的列表視圖中的Java

otherAdapter adapter = new otherAdapter(getActivity(), R.layout.grid_single, result); 
      grid_list.setAdapter(adapter); 
      grid_list.setOnItemClickListener(new AdapterView.OnItemClickListener() { // list item click opens a new detailed activity 
       @Override 
       public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
        otherModel othermodel = result.get(position); 
        Bundle bundle = new Bundle(); 
        bundle.putString("otherModel",new Gson().toJson(othermodel)); 
        OtherDetail other = new OtherDetail(); 
        other.setArguments(bundle); 
        getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container,new OtherDetail()).addToBackStack(null).commit(); 
       } 

,並在我的片段的java我使用getArgument試圖調用數據。

Bundle bundle = this.getArguments(); 
    if(bundle != null) { 
     String json = bundle.getString("otherModel"); // getting the model from MainActivity send via extras 
     otherModel otherModel = new Gson().fromJson(json, otherModel.class); 
} 
+0

查看[此鏈接](https://developer.android.com/training/basics/fragments/communicating.html)活動片段通信。 –

+0

爲什麼你不通過使用putSerializable()來傳遞其他模型的對象? –

回答

0

您必須在事務中傳遞「other」,您不必創建新的片段。 在事務中創建片段時,您無需發送參數即可發送片段。

+0

非常感謝!它爲我工作! – JsLaw

0

其實問題是,您可以設置不同對象參數和通過爲交易是不同的,因此傳遞相同的對象無論是在簡單的一句話,如果你設置other一個參數然後傳遞同一個對象進行交易。

用以下代碼替換此行。

getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container,other).addToBackStack(null).commit(); 
+0

非常感謝!它爲我工作! – JsLaw

相關問題