如何将一些数据转移到另一个片段同样,它是做了额外的意图?


当前回答

来自活动课:

使用bundle参数将数据发送到片段并加载片段

   Fragment fragment = new myFragment();
   Bundle bundle = new Bundle();
   bundle.putString("pName", personName);
   bundle.putString("pEmail", personEmail);
   bundle.putString("pId", personId);
   fragment.setArguments(bundle);

   getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                    fragment).commit();

从myFragment类:

从bundle中获取参数并将它们设置为xml

    Bundle arguments = getArguments();
    String personName = arguments.getString("pName");
    String personEmail = arguments.getString("pEmail");
    String personId = arguments.getString("pId");

    nameTV = v.findViewById(R.id.name);
    emailTV = v.findViewById(R.id.email);
    idTV = v.findViewById(R.id.id);

    nameTV.setText("Name: "+ personName);
    emailTV.setText("Email: "+ personEmail);
    idTV.setText("ID: "+ personId);

其他回答

为了进一步扩展前面的答案,就像Ankit说的,对于复杂的对象,你需要实现Serializable。例如,对于简单对象:

public class MyClass implements Serializable {
    private static final long serialVersionUID = -2163051469151804394L;
    private int id;
    private String created;
}

在你的FromFragment中:

Bundle args = new Bundle();
args.putSerializable(TAG_MY_CLASS, myClass);
Fragment toFragment = new ToFragment();
toFragment.setArguments(args);
getFragmentManager()
    .beginTransaction()
    .replace(R.id.body, toFragment, TAG_TO_FRAGMENT)
    .addToBackStack(TAG_TO_FRAGMENT).commit();

在你的ToFragment:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

    Bundle args = getArguments();
    MyClass myClass = (MyClass) args
        .getSerializable(TAG_MY_CLASS);

getArguments()返回null因为“它没有得到任何东西”

试试这段代码来处理这种情况

if(getArguments()!=null)
{
int myInt = getArguments().getInt(key, defaultValue);
}

如果你使用图表在片段之间导航,你可以这样做:

    Bundle bundle = new Bundle();
    bundle.putSerializable(KEY, yourObject);
    Navigation.findNavController(view).navigate(R.id.fragment, bundle);

片段B:

    Bundle bundle = getArguments();
    object = (Object) bundle.getSerializable(KEY);

当然你的对象必须实现Serializable

只是扩展一下前面的答案——它可以帮助到一些人。如果你的getArguments()返回null,把它放在onCreate()方法,而不是你的片段的构造函数:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    int index = getArguments().getInt("index");
}

这是你使用bundle的方式:

Bundle b = new Bundle();
b.putInt("id", id);
Fragment frag= new Fragment();
frag.setArguments(b);

从bundle中检索值:

 bundle = getArguments();
 if (bundle != null) {
    id = bundle.getInt("id");
 }