在片段之间传递对象 [英] Passing objects between fragments

查看:128
本文介绍了在片段之间传递对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用带有三个片段菜单的内置导航抽屉活动,我想通过这些片段进行通信,这意味着要将数据从一个传递到另一个.我发现有三种与片段进行通信的方式.我也清楚地了解到该片段永远不会直接通信.

Iam using build-in Navigation drawer activity with three fragment menus, I want to communicate over those fragments means wants to pass data from one to another. And I found there is a three possible way to communicating with fragments. Also I have understood clearly that the fragment never communicate directly.

  • 使用界面
  • 全局类(扩展应用程序类)
  • 最终使用捆绑包

现在,我的问题是与片段进行通信的最佳方式,目前Iam使用second method将所有这些对象放入Globalized objects which extends Application Class.这是正确的方法吗?

And now my question is which is the best way to communicate with fragments, currently Iam using second method which is I put(getter&setter class) all those object to the Globalized objects which extends Application Class. Is this the right approach or not??

推荐答案

您可以在Object类中实现Serializable,然后只需使用捆绑包将其传递即可.我假设您正在从first_fragment中启动second_fragment.

You can implement Serializable in your Object class and then pass it simply using bundles. I'm assuming you're launching the second_fragment from your first_fragment.

在您的第一个片段中:

FragmentTransaction ft =  getActivity().getSupportFragmentManager().beginTransaction();
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
Fragment2 fragment2 = new Fragment2();

Bundle bundle = new Bundle();
YourObj obj = SET_YOUR_OBJECT_HERE;
bundle.putSerializable("your_obj", obj);
fragment2.setArguments(bundle);
ft.replace(android.R.id.content, fragment2);
ft.addToBackStack(null);
ft.commit();

在第二部分中:

Bundle bundle = getArguments();
YourObj obj= (YourObj) bundle.getSerializable("your_obj");

编辑

要序列化对象,只需在Object类中实现Serializable.

To Serialize your object, simply implement Serializable in your Object class.

如果您的对象类是YourObj.class

If your Object class is YourObj.class

public class YourObj implements Serializable {
    int id;
    String name;

    // GETTERS AND SETTERS
}

这篇关于在片段之间传递对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆