-
扬帆大鱼
用Bundle..下面是一个例子:Fragment fragment = new Fragment();Bundle bundle = new Bundle();bundle.putInt(key, value);fragment.setArguments(bundle);bundle为许多数据类型提供了方法。看见这,这个然后在你的Fragment,检索数据(例如,在onCreate()方法)与:Bundle bundle = this.getArguments();if (bundle != null) {
int myInt = bundle.getInt(key, defaultValue);}
-
慕仙森
为了扩展前面的答案,就像Ankit所说的,对于复杂的对象,您需要实现Serialable。例如,对于简单对象:public class MyClass implements Serializable {
private static final long serialVersionUID = -2163051469151804394L;
private int id;
private String created;}在你身上: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();在你的房间里:@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Bundle args = getArguments();
MyClass myClass = (MyClass) args .getSerializable(TAG_MY_CLASS);
-
慕勒3428872
使用片段到片段传递数据的完整代码Fragment fragment = new Fragment(); // replace your custom fragment class Bundle bundle = new Bundle();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
bundle.putString("key","value"); // use as per your need
fragment.setArguments(bundle);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.replace(viewID,fragment);
fragmentTransaction.commit();在自定义片段类中Bundle mBundle = new Bundle();mBundle = getArguments();mBundle.getString(key);
// key must be same which was given in first fragment