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

荒凉一梦 提交于 2019-12-08 11:56:29

问题


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.


回答1:


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();
}



回答2:


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.




回答3:


  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



来源:https://stackoverflow.com/questions/43175820/transfer-data-from-fragment-a-fragment-b-fragment-c-when-user-click-back

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