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


当前回答

这是你使用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");
 }

其他回答

这是你使用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");
 }

如果你正在使用kotlin,那么你可以传递bundle as

val fragment = YourFragment()
val bundle = Bundle().apply {
    putInt("someInt", 5)
    putString("someString", "Hello")
}
fragment.arguments = bundle

在YourFragment的onCreate中获取这些值

this.arguments?.let {
    val someInt    = it.getInt("someInt", someDefaultInt)
    val someString = it.getString("someString", someDefaultString)
}

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

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

为了进一步扩展前面的答案,就像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);

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

    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