0

I'm learning about fragments I have some doubts. Consider following code:

FragmentManager fm = getFragmentManager();  
Fragment MyFragment = new Fragment();  
fm.beginTransaction().replace(R.id.my_container, MyFragment).addToBackStack(null).commit();

My question is:

  1. what exactly does replace do?
  2. What happens if I create many fragments this way (to replace previous ones in a container).
  3. Can it in any way be bad for memory usage?
  4. Is it considerably better just to change fragment's content?
ישו אוהב אותך
  • 28,609
  • 11
  • 78
  • 96
TomekK
  • 403
  • 1
  • 4
  • 11
  • For the first question: http://stackoverflow.com/questions/18634207/difference-between-add-replace-and-addtobackstack – Iulian Popescu Oct 19 '16 at 08:21
  • It doesn't really help. I've found basic informations about it, but I'm thinking about details. Like what happens to replaced fragments, is keeping them memory heavy etc. – TomekK Oct 20 '16 at 10:27

2 Answers2

0
  1. Replace removes all the fragments that are in the container and adds the new fragment to the container. (if there isn't a fragment in the container then it just adds the new one).
  2. If you create many fragments this way then every transaction is saved to the backstack so you can reverse the transaction by pressing the back button.
  3. The only thing you can do is to create a variable fragmentTransaction and use the fm.beginTransaction() only once and not every time you want to replace the fragment in the container.
  4. I don't think so, fragments should be modular and reusable.

You can read more here: https://developer.android.com/guide/components/fragments.html

T.S
  • 911
  • 8
  • 24
0
  1. it simple put another "layer" on container.
  2. appcrash
  3. yes
  4. No, fragment is the easiest way.

Using fragment & backstack tag to reference to a Fragment if you want to call fragment again and process Back button.

fm.beginTransaction().replace(R.id.my_container, MyFragment, "FRAGMENT_TAG").addToBackStack("FRAGMENT_BACKSTACK_TAG").commit();
PLe
  • 137
  • 4