简体   繁体   English

将Parcelable对象从片段传递到另一个片段

[英]Passing Parcelable objects from fragment to another fragment

I have two fragment one creating in onCreateView and other creating in onViewCreated 我在onCreateView中创建了两个片段,在onViewCreated中创建了其他片段

Fragment A in onCreateView has 3 editText felds onCreateView中的片段A有3个editText字幕

Fragment B in onViewCreated has a recyclerview with list items (having firstname,lastname for each item) On click of that item I will pass an parcelable object the fragment A which has edit text fields and want to display those data int editText fields onViewCreated中的片段B有一个带有列表项的recyclelerview(每个项目都有firstname,lastname)点击该项目后,我将传递一个parcelable对象片段A,它具有编辑文本字段并希望在editText字段中显示这些数据

How do I achieve this ? 我该如何实现这一目标?

Fragment fragmentGet1 = new FragmentGet1();
Fragment fragmentGet2 = new FragmentGet2();
Fragment fragmentGet2 = new FragmentGet3();

fragmentGet1.setArguments(bundle);
fragmentGet2.setArguments(bundle);
fragmentGet3.setArguments(bundle);

You can create instances of all the 3 fragments, but then only using the instance of FragmentGet1. 您可以创建所有3个片段的实例,但只能使用FragmentGet1的实例。 The other ones are not used. 其他的不使用。 Later, when you create another instance of any of those Fragments, it will not have the args because it is a totally separate object. 稍后,当您创建任何这些片段的另一个实例时,它将没有args,因为它是一个完全独立的对象。

That you need is to pass the bundle forward each time you create a new Fragment. 您需要的是每次创建新片段时都向前传递包。 If you want to create it from within an already-created fragment, it will look somewhat like this: 如果你想在已经创建的片段中创建它,它看起来会像这样:

public void showNextFragment() {

    FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

    Fragment fragmentGet2 = new FragmentGet2();

    if(this.getArguments() != null)
        fragmentGet2.setArguments(this.getArguments());

    fragmentTransaction.replace(R.id.frame_container, fragmentGet2);
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commit();

}

Example

To pass the Student object to an Activity, just do something like this: 要将Student对象传递给Activity,只需执行以下操作:

Student s = //get it here
Bundle b = new Bundle();
b.putParcelable("student", s);

Intent i = new Intent(getActivity(), ThatOtherActivity.class);
i.putExtra("extraWithStudent", b);
startActivity(i);

And then to read the data in the Activity: 然后读取Activity中的数据:

Intent incomingIntent = getIntent();
Bundle b = incomingIntent.getBundleExtra("extraWithStudent");
Student s = (Student) b.getParcelable("student");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM