简体   繁体   中英

transfer data from fragment A -> fragment B - > fragment C. When user click Back button, I want to return to fragment A and data

I'm a newbie in android developer. I have a question about transfer with 3 fragments.

I have 3 fragments (A - B - C). I want o transfer data from A -> B -> C.
In each the fragment, data was been changed. When user click BACK BUTTON, user want to return A with the updated data. How to return fragment A with the update data? Thanks.

Use interface to achieve this. Implements interface in fragment and activity, as it's a good way to communicate between fragment through activity. Then send the data through interface and extract the data from it.

  1. You can use Interface class to communicate between fragment but it must make sure all the fragment is alive.

  2. You can use SharedPreferences where you can save the data and retrieve it anywhere you like

Here is a sample idea how to achieve communication.

 // activity classs
 public class SampleActivity extends Activity implements    OnFragmentChangeListener {
 OnBackPressListener  dataFragment;
 public void onCreate(bundle){

      android.app.FragmentManager fragmentManager=getFragmentManager();

    android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

    dataFragment = new DataFragment();
    fragmentTransaction.add(R.id.audio_permission_button,dataFragment);
    fragmentTransaction.commit()
 }
  @override
  public void OnFragmentChange(Bundle bundle){
  //here you go.
  // write code to load new fragment with same idea. now you have bundle do what you want.

}
@Override
public void onBackPressed() {
 // you can call this method from any click event, This just an sample idea.
 dataFragment.OnActivityBackPress();
}

}
 // interface to communicate with fragment
 public interface OnFragmentChangeListener {
     public void OnFragmentChange()
 }
 // fragment class
public class DataFragment extends Fragment implements OnBackPressListener {

 OnFragmentChangeListener onFragmentChangeListener;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
 onFragmentChangeListener=(OnFragmentChangeListener) getActivity();


}

    @Override
public void OnActivityBackPress() {
 // pass you data to activity for loading new fragment or to refresh data.
 Bundle bundle= new Bundle();

 onFragmentChangeListener.OnFragmentChange(bundle);



}
}

// interface behave like mediator 
public interface OnBackPressListener {

public void OnActivtiyBackPress();
}

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