将多个 Bundle 传递给片段 [Android]

Passing more than a Bundle to a fragment [Android]

是否可以在传递到 Android 上的片段之前将两个包合并为一个包? 所以代码片段类似于:

  Bundle b1 = SomeClass1.getSomeBundle();
  Bundle b2 = SomeClass2.getDifferentBundle();
  // How to do I pass these two bundles to a fragment?
  fragment.setArgument(b1 + b2); // Illustrative only.

Is it possible to combine two bundles into one before passing to a fragment on Android?

是的,您可以使用 Bundle.putAll(Bundle bundle)

或者您可以通过使用 Bundle.putBundle(String key, Bundle value)

创建捆绑包来分别传递两个捆绑包

Bundle 也可以包含 Bundle。您可以使用 putBundle

 Bundle b1 = SomeClass1.getSomeBundle();
 Bundle b2 = SomeClass2.getDifferentBundle();
 b1.putBundle("b2", b2);
 fragment.setArgument(b1);

要检索它,您可以使用 getBundle(String key)

  Bundle b1 = getArguments();
  Bundle b2 = b1.getBundle("b2");

Bundle 可以包含 Bundle

Bundle mainBundle = new Bundle();
Bundle b1 = SomeClass1.getSomeBundle();
Bundle b2 = SomeClass2.getDifferentBundle();

mainBundle.putBundle("b1", b1);
mainBundle.putBundle("b2", b2);

fragment.setArgument(mainBundle);

要从捆绑包中获取捆绑包,只需调用:

Bundle b1 = mainBundle.getBundle("b1");
Bundle b2 = mainBundle.getBundle("b2");