0

I have 2 fragments, FragmentB & FragmentC which are inherit from FragmentA. and MainActivity with supportFragmentManager to switch between fragments. In FragmentB & FragmentC the user can insert his name to EditText. each fragment has it's own EditText on it's layout. but when I switch between the fragments I want the current value will be equal on both fragments. so if the user input on FragmentB the name "ab" and switch to FragmentC he will see "ab" on the EditText and can append "c" so when he will switch back to FragmentB he will see "abc" on the EditText. I've mentioned that both of the fragments are inherit from FragmentA and I thought to do this by declaring protected EditText on FragmentA so both FragmentB and FragmentC will initialize the EditText. and to add TextWatcher to this EditText but the text is not updated properly while switching the fragments. any other ideas, how can I really create shared EditText so both of the fragments will change and read it's value on realtime?

Elior
  • 3,178
  • 6
  • 37
  • 67
  • 3
    Possible duplicate of [How to pass values between Fragments](https://stackoverflow.com/questions/16036572/how-to-pass-values-between-fragments) – ADM Oct 28 '18 at 16:17
  • @ADM thanks! it helped! – Elior Oct 28 '18 at 17:28

1 Answers1

0

In your activity, add these:

private String userName;

private String getUserName() {
    return userName;
}

private void setUserName(String userName) {
    this.userName = userName;
}

You may also want to save/restore userName via onSaveInstanceState() etc, but for now we can skip worrying about that.

In both of your fragments, add this:

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    MyActivity activity = (MyActivity) getActivity(); // replace with your activity class name
    nameEditText.setText(activity.getUserName()); // replace with your EditText
}

And in your TextWatcher, set the value back to the activity:

@Override
public void afterTextChanged(Editable s) {
    MyActivity activity = (MyActivity) getActivity(); // replace with your activity class name
    activity.setUserName(s.toString());
}
Ben P.
  • 52,661
  • 6
  • 95
  • 123