将对象传递给没有参数的片段 [英] Passing Objects to fragment without argument

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

问题描述

如果我在不使用 bundle 的情况下将 object 传递给 fragment ,将产生什么含义?我只是打开一个旧代码,然后在那找到了它,因为我从未尝试过,所以不禁要问这个问题.另外,我也没有发现任何内存泄漏.

What will be the implications if I passed an object to a fragment without using bundle? I just opened one of the old code and found it there and couldn't help asking this question as I have never tried it. Also I am not finding any memory leaks in it.

这是它的实现方式-

活动分类:

MyFragment fragment =
        MyFragment.newInstance(getIntent().getStringExtra(DATA),
            instance.getCallback(),
            instance.getRequest());
    getSupportFragmentManager().beginTransaction().replace(R.id.content, fragment).commit();

片段类:

public class MyFragment extends Fragment {

  public MyFragment() {
    /* Required empty public constructor */
  }

  public static MyFragment newInstance(String data, Callback callback,
      Request request) {
    MyFragment fragment = new MyFragment();
    fragment.setCallback(callback);
    fragment.setRequest(request);
    fragment.setData(data);
    return fragment;
  }

  private void setCallback(Callback callback) {
    this.callback = callback;
  }

  private void setData(Data data) {
    this.data = data;
  }

  private void setRequest(Request request) {
    this.request = request;
  }
}

通常,直到现在我一直使用的是 Fragment#setArguments(Bundle)

Generally, what I have used till date is Fragment#setArguments(Bundle)

推荐答案

请查看以下答案:

Please check out this answer: Why its not recommended to pass object to fragment with simple getter setter.

长话短说,您将丢失有关配置更改的数据.

Long story short, you will lose your data on configuration changes.

与片段进行通信的方式主要有两种:通过捆绑包或通过您在活动中实现的接口.请查看此链接,以了解如何通过接口与片段正确通信: https://developer.android.com/training/basics/fragments/communication

There are mainly two ways of communicating with a fragment: via bundles or via an interface that you implement in your activity. Please see this link in order to see how to properly communicate with a fragment via an interface: https://developer.android.com/training/basics/fragments/communicating

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

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