1

Lets say I have 2 fragments, one of which has a text input field.

I switch between my fragments in the main activity with this:

public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_new) {
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

            fragmentTransaction.replace(R.id.fragment_container, NewFragment(), fragment.getClass().getSimpleName())
                        .addToBackStack(Integer.toString(id))
                        .commit();
        } ...

Notice I'm using framentTransactions replace method

On the current fragment with the input box, I type in some text. Then I use the nav bar to switch to a new fragment. I would expect that because I'm using replace, the old fragment no longer exists.

I navigate to the new fragment fine, but when I press the back button, the old fragment still has the text that I typed in previously

Why would this happen when using replace? Am I misunderstanding how fragment transactions work?

Does the onCreateView method of the fragment not get called again when I press back, thus essentially resetting the fragment?

Simon
  • 9,762
  • 15
  • 62
  • 119
  • the back stack will retain the fragment so you can hit the back button to go back to it, try not adding it to the back stack, or manually clear the text field when the fragment is detached. – ootinii Feb 27 '16 at 05:06

1 Answers1

0

You have to clear your textfied manually when you switching to another fragment

Because fragment replace is only replace fragment but still your old fragment is there without any change .

Uttam Panchasara
  • 5,735
  • 5
  • 25
  • 41
  • does `onCreateView` still get called when pressing back into a fragment? – Simon Feb 27 '16 at 07:53
  • 1
    `onCreateView()` get called only after your `onAttach()` and `onDestroyView()` if you are still on same fragment. [See Here](http://stackoverflow.com/questions/24156926/oncreateview-method-gets-called-when-and-how-many-times-in-activity-life-cycle) – Uttam Panchasara Feb 27 '16 at 08:59