简体   繁体   中英

Passing Parcelable objects from fragment to another fragment

I have two fragment one creating in onCreateView and other creating in onViewCreated

Fragment A in onCreateView has 3 editText felds

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

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. 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.

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 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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