简体   繁体   中英

Passing data from one fragment to another when second fragment already has data

So, I have a fragment A, and a fragment B. Fragment A has some data, user presses a Button, goes to fragment B, performs some actions there, and when he is done I need the user to go back to fragment A with some data recovered from fragment B, while the data in fragment A is not recreated, but keeps the data it had in the first time. This shouldn't be so hard, but I am having some problems achieving it.

I can, of course, call fragment A from fragment B, but the data previously existing in fragment A is erased. Or I can go through the backstack to present fragment A again, but how could I pass data from fragment B while maintaining data present in fragment A?

both Fragment s are attached to same Activity , so you can introduce some methods in it

private String data = null;

public void storeData(String data){
    this.data = data;
}

public void restoreData(){
    return data;
}

and call from Fragment s side

// when B is detached/removed
((MainActivity) getActivity()).storeData(data);

// onCreateView of A?
String restoredData = ((MainActivity) getActivity()).restoreData(); 
if (restoredData!=null) ...

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