0

I have code like this to take my currently shown fragment in my activity and show a different fragment. Sometimes the first view is displayed on top of the other view.

What could cause that? Is there a better way to do this?

    android.app.FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
    fragmentTransaction.remove(from);
    fragmentTransaction.commit();
    getFragmentManager().executePendingTransactions();
    fragmentTransaction = getFragmentManager().beginTransaction();

    fragmentTransaction.add(R.id.container, to);
    if(showBackButton) {
        fragmentTransaction.addToBackStack(to.toString());
    }
    fragmentTransaction.commit();
Maestro1024
  • 3,173
  • 8
  • 35
  • 52

1 Answers1

0

You might try the replace command instead. Something like:

FragmentTransaction transaction = fm.beginTransaction();
transaction.replace(R.id.fragment_container, iFrag);
transaction.commit();

The fragment_container is just a FrameLayout inside its own XML file:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="?android:attr/actionBarSize"
android:background="#888888" />

iFrag is an instantiated class that extends Fragment.

JASON G PETERSON
  • 2,193
  • 1
  • 18
  • 19
  • Where does the anim ids come from ? – Maestro1024 Dec 08 '14 at 14:46
  • I tried something like this before and couldn't figure out how to build the container. I created a method here where different fragments pass them selves in. Not sure how to create the container without having the named container (can I create it dynamically?) – Maestro1024 Dec 08 '14 at 14:48
  • Sorry, animations are optional and I've removed them. I've also add a few more details to the answer to hopefully make it clearer. I'm pretty sure replace will do the trick for you as I remember similar issues when trying to use remove/add. – JASON G PETERSON Dec 08 '14 at 14:54
  • So fragment_container is where iFrag will go? You don't actually have to remove the old fragment? – Maestro1024 Dec 08 '14 at 15:15
  • I don't think so. Not in my case anyway -- sorry, it's been a while since I coded this part of my app. There are some more details here (http://stackoverflow.com/questions/5658675/replacing-a-fragment-with-another-fragment-inside-activity-group). So long as you dynamically create your fragments this should work for you. There's a link on the answer to a fuller tutorial as well. – JASON G PETERSON Dec 08 '14 at 15:26