How can i correctly interact between Activities and fragments

寵の児 提交于 2020-01-17 06:57:07

问题


I'm working with Steppers. So currently i have one Activity with 3 Fragments in which the user must complete with some information, like a Form. There are a lot of information so i made 4 classes to separate that information. In addition, some information is got it automatically so in fragments i ask for permissions... For Example:

public class UserIds {
@Nullable
@Expose  String phone;
@Expose String Email;
@Expose String phone2;
@Expose String ModCel;
@Expose String Doc;


//Setters, getters and another simple method

public class UserLocation {
@Nullable
@Expose  String street;
@Expose int number;
....

//Setters, getters and another simple method

...

And so on with 2 classes more.

So, as you can see i'm working with retrofit too.

How can I correctly handle something like that? I read about Parceler , Interfaces, EventBus... Should I declare all objects instances in the Activity and then modify in each fragment ( Some objects are modified by differents fragments) or maybe create instances in each fragment, store the information and in when the Complete button is pressed, obtain the information? How should i save this objects in case of OnDestroy() call?

Another things to take into account is that finally, when the form is end. Other activity may have all the information and ask for more (yeah, a LOT OF INFORMATION IS NEEDED).

Finally, every time the user complete the form (with the complete button and then when the other activity ask for more, this data is sended to the server)


回答1:


I chose the Parceler way and work perfectly. Maybe help somebody, i put @Parcel in each POJO class, then as i am handling with fragments with StepperAdapter (because of stepstone library) in the fragment which i want to save data i did this:

    // Obtaing all the fragments 
    List<Fragment> steps = getFragmentManager().getFragments();
    // save states
    Bundle bundle = new Bundle();
    Parcelable wrapped = Parcels.wrap(obj1);
    Parcelable wrapped2 = Parcels.wrap(obj2);
    bundle.putParcelable("OBJ1", wrapped);
    bundle.putParcelable("OBJ2", wrapped2);
    steps.get(fragment2reference).getArguments().putAll(bundle);

Then in the fragment that receive, you have to create a constructor and then you can receive the data (because of fragment was already created, so the bundle throw error)

//Constructor
public fragment2(){
    super();
    setArguments(new Bundle());
}

When fragment2 shows :

   OBJ1 a = Parcels.unwrap(getArguments().getParcelable("OBJ1"));
   OBJ2 b = Parcels.unwrap(getArguments().getParcelable("OBJ2"));

Hope somebody help!



来源:https://stackoverflow.com/questions/45062320/how-can-i-correctly-interact-between-activities-and-fragments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!