2017-06-12 65 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