Search code examples
androidandroid-fragmentsinstances

Android fragment instances avoid duplicates


Hi I am not sure I am doing the right thing. I have several fragments in one activity (not shown at the same time). When I add the fragment do I have to check if a previous instance exists? I am using the compatibility package and my fragment CameraFragment is a separate class (in its own file):

private void addNewFragment(Fragment fragment, String tag) {
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    ft.replace(R.id.frag1, fragment, tag);
    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
    ft.addToBackStack(null);
    ft.commit();
}

and then :

public void startPicTaking() {

    addNewFragment(CameraFragment.newInstance(), TAG_PIC_TAKING);

}

So each time a user clicks a button to take a picture I use this methods BUT shall I verify if the fragment already exists and remove it first or does the static method newInstance make sure the fragment is not duplicated?

I have read the doc several times but I don't understand why the line: ft.addToBackStack(null); what is it for? I know you can pop the back stack and it keeps the transaction but how can it be used and for what? Is it necessary or if I don't use it I can skip it?

thanks


Solution

  • I have several fragments in one activity (not shown at the same time). When I add the fragment do I have to check if a previous instance exists?

    No, it will just create a new instance of that Fragment when it adds the next instance of it. It will not affect the previous instance of it.

    So each time a user clicks a button to take a picture I use this methods BUT shall I verify if the fragment already exists and remove it first or does the static method newInstance make sure the fragment is not duplicated?

    You could do that if you wanted to, to ensure that no Fragment appears twice in the stack. (So when you hit back, you don't get the same activity again.) Depending on exactly what appears in your back stack, you may not want to remove stuff lower down. (Consider that a user expects previous fragments to appear when he hits the back button.)

    I have read the doc several times but I don't understand why the line: ft.addToBackStack(null); what is it for?

    When Fragment objects are added to the back stack, then each time the user hits back, they will go to the previous item on the stack. If you do not add an item to the back stack, the user will not encounter it when they hit the back button.