12

The scenario I am faced with, is in my application I have a single pane and dual pane style layout. Rather than individually handle every single navigation operation possible between the screens, for every different style of layout, I am using a function which sets up the layout correctly when given the desired screen.

It is basically a switch statement for each screen in the app, with a nested switch statement in each screen to handle each layout style. This is what I'm talking about in code:

protected void setupScreen() {
    switch(currentScreen) {
    case SCREEN_ONE:
        switch(currentLayout) {
        case SINGLE_PANE:
            // Perform actions to setup the screen
            break;
        case DUAL_PANE:
            // Perform actions to setup the screen
            break;
        }
        break;
    case SCREEN_TWO:
        switch(currentLayout) {
        case SINGLE_PANE:
            // Perform actions to setup the screen
            break;
        case DUAL_PANE:
            // Perform actions to setup the screen
            break;
        }
        break
    // ... etc ....
    }
}

In the section where I want to perform the actions to setup the screen, this consists of the following basic three operations:

// Create the fragments if necessary
if (screenFragment == null) {
    screenFragment = new myFragment();
}

// Remove the existing fragments from the layout views
// HOW???

// Add the fragments for this screen to the view
getSupportFragmentManager().beginTransaction().add(pane1.getId(), myFragment, "myFragment").commit();

As you can see, what I am struggling with is how to do the second step. How do you remove all Fragments from a given View without knowing exactly which ones you are wanting to remove? The closest I have found is FragmentTransaction.replace() which does successfully do this for every case but when it turns out you are replacing a Fragment with the same fragment. In this case, it does not remove all, then add (like the documentation suggests), it just seems to remove. Is this an issue with using the compatibility libraries or is it not the way FragmentTransaction.replace() should be used?

In any case, how should I go about doing this? Do I have to code a removeAllFragments() function to go through every fragment and detach it or is there a way to do the first half of what the 'two in one' FragmentTransaction.replace() function claims to do?

5 Answers 5

20

None of the other answers were really working for me. Here's what I did:

List<Fragment> al = getSupportFragmentManager().getFragments();
if (al == null) {
   // code that handles no existing fragments
   return;
}

for (Fragment frag : al)
{
   // To save any of the fragments, add this check.
   // A tag can be added as a third parameter to the fragment when you commit it
   if (frag == null || frag.getTag().equals("<tag-name>")) {
      continue;
   }

   getSupportFragmentManager().beginTransaction().remove(frag).commit(); 
}

or, if you're forced to use it (but not recommended):

.commitAllowingStateLoss();

Also, if you're removing all fragments from the view multiple times, you might consider checking if the current frag is null or isDetached() or isRemoving() or you might get NullPointerExceptions.

Update: The documentation for getSupportFragmentManger().getFragments() is apparently hidden now, but still works just fine in my code. Here's the screenshot of the documentation:

enter image description here

Having said that, since it is hidden, they no longer want this method used, so see my update below.

Update 8-4-15: If you're not using the support library for fragments, there is unfortunately no getFragments() available, but there are still a couple, more inconvenient, options.

  1. Give each fragment a tag or id upon creation, and iterate through them to process each fragment as desired.
  2. Create a listener using onAttachListener so each time a new fragment is attached to the activity, you can store that fragment, and then iterate through that data structure to process each fragment as desired.

When not using the getSupportFragmentManager(), to process a transaction you will need to use getFragmentManager() instead.

5
  • Actually, there is; it's just been hidden since this answer was written. And it still works. Try it.
    – craned
    Commented Aug 4, 2015 at 2:36
  • It's not true. It's presented only in support library since 4.3, however it's not presented in android.app.FragmentManager. Answer is leading in wrong direction and applicable only for support library (with additional mentions about usage of hidden API).
    – sandrstar
    Commented Aug 4, 2015 at 2:57
  • 3
    Oh, I didn't realize you were talking about using the normal FragmentManager, rather than the SupportFragmentManager. You're right; there is no getFragments() for android.app.FragmentManager. See my updated answer.
    – craned
    Commented Aug 4, 2015 at 12:10
  • your code have a few Exceptions pit falls, it is better to add the following if's: if(al != null && al.size()>0) And if (frag.getTag() != null)
    – Gal Rom
    Commented Jan 16, 2017 at 21:09
  • I disagree. I check first if al == null and handle that; I'll add a return;. I don't need to check if ai.size() > 0 because the for loop handles that. If it's empty, the inner code is never run, which should also mean that the frag != null, but that is a good idea to check, as the programmer might make a mistake there.
    – craned
    Commented Jan 17, 2017 at 12:37
7

The typical mechanism is to use FragmentManager.findFragmentByTag() . You use this and add tags to your fragments (or the alternative for id's). This way you can determine what fragments are currently being managed. Then, once you have a handle to a present fragment (findFragmentByTag returns non-null), you can use FragmentManager.beginTransaction() to start a FragmentTransaction and remove / add the necessary fragments. Working in this way will allow you to avoid the 're-adding' process for the fragment you want to keep.

What I'd probably do is have code like so: (warning psuedo code)

Fragment pane1 = FragmentManager.findFragmentByTag("myFragmentPane1");
Fragment pane2 = FragmentManager.findFragmentByTag("myFragmentPane2");

setupScreen(pane1, pane2);

You should also consider sub-classes of your class instead of having 'everything in one class'. You have a fairly obvious case of Martin Fowler's Replace Conditional with Subclass. Otherwise, I fear this is going to be incredibly hard to manager when you add another screen.

1
  • +1, sounds dumb, but have never thought of using the Tag to identify where the fragment is placed, always used it to identify what type the fragment is
    – btalb
    Commented Feb 9, 2013 at 6:01
3

If you use android.support.v4.app.Fragment you can do this:

List<Fragment> fragments = getSupportFragmentManager().getFragments();
if (fragments != null) {
    for (Fragment fragment : fragments) {
        getSupportFragmentManager().beginTransaction().remove(fragment).commit();
    }
}
2
  • Doesn't work? it says it requires android.app.Fragment
    – Kahn Kah
    Commented Jun 24, 2016 at 21:21
  • @KahnKah ... you have to use getFragmentManager() in your use case
    – Devrath
    Commented Jan 1, 2019 at 12:37
1

Turns out FragmentTransaction.replace() is the correct operation and should work correctly. It only does not work when using ActionBarSherlock and SherlockFragmentActivity so I can only assume it is a bug in this compatibility library.

I have confirmed this through using the code below to implement the desired behaviour through Android on API11+, the android compatibility library, and ActionBarSherlock. It only breaks in the last instance.

package com.test.test;

import com.actionbarsherlock.app.SherlockFragmentActivity;

import android.os.Bundle;
import android.content.Context;
import android.graphics.Color;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

public class MainActivity extends SherlockFragmentActivity {
  // Consistent fragment instance
    myFragment myFrag = null;

    // Views
    FrameLayout fl = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        LinearLayout ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);

        Button b = new Button(this);
        b.setText("Repeat");
        b.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                // Reattach the same fragment
                getSupportFragmentManager().beginTransaction().replace(fl.getId(), myFrag).commit();

            }
        });

        fl = new FrameLayout(this);
        fl.setId(200);
        fl.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

        myFrag = new myFragment();
        getSupportFragmentManager().beginTransaction().add(fl.getId(), myFrag).commit();

        ll.addView(b);
        ll.addView(fl);

        setContentView(ll);
    }

    public static class myFragment extends Fragment {

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            TextView tv = new TextView(getActivity());
            tv.setText("My fragment");
            tv.setGravity(Gravity.CENTER);
            tv.setBackgroundColor(Color.RED);

            return tv;
        }
    }

}
0
0

This is more or less how I have handled this. Have all your fragments implement an interface something like:

public interface NamedFragment{

    public FragmentName getFragmentName();

}

Make an enum corresponding to your fragments:

public enum FragmentName{

    SOME_FRAGMENT,
    SOME_OTHER_FRAGMENT;

}

Then in your fragment switching activity:

// Get the manager and transaction separately so you can use both: 
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction ft = fragmentManager.beginTransaction();

// Get a reference to the fragment(s) currently in the container(s)
    Fragment currentFragment = fragmentManager.findFragmentById(position);

    FragmentName cFragmentName =
            ((NamedFragment) currentFragment).getFragmentName();
    Fragment nextFragment =
            Fragment.instantiate(this, some_new_fragment_string);
    FragmentName nFragmentName =
            ((NamedFragment) nextFragment).getFragmentName();
// Compare the "names"
    if(cFragmentName != nFragmentName){
        ft.replace(position, nextFragment);
    }

You'll have to change things around a little to fit your particulars.

1
  • My answer makes sense if you only ever want one instance of a given class at a time; @Nick's makes sense if you need unique identifiers for each instance.
    – anthropomo
    Commented Feb 8, 2013 at 3:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.