1

I have an app that is extending ActionBarActivity and is using google maps as fragment. I obtain the map like this:

SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mMap = fm.getMap();

So my question is, how to add another fragment and how to switch between them ? I've been googling and searching for solution but found nothing yet.

Lukas Anda
  • 716
  • 1
  • 9
  • 30

1 Answers1

0

Use FragmentTransaction.replace() to replace fragments. Example:

Fragment newFragment = new MyFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, newFragment);
transaction.commit();

For more check this answer too.

If you are using a support package (v4, v7 or v11) or you are targeting API< 14 use getSupportgetSupportFragmentManager(). Else, for API>=14 use getFragmentManager().

Community
  • 1
  • 1
Menelaos Kotsollaris
  • 5,776
  • 9
  • 54
  • 68
  • I suggest to add transaction.addToBackStack(null); before transaction.commit(); this will ensure that when you press back button the current one will disappear and the one before it will show. – Karim May 14 '15 at 16:16
  • Thanks, going to try it. Just one question. cna i use getSupportFragmentManager() instead of getFragmentManager() ? – Lukas Anda May 14 '15 at 18:39
  • if you use API>14, you [should use](http://stackoverflow.com/questions/12380367/getsupportfragmentmanager-versus-getfragmentmanager-in-android-3-0) `getFragmentManager`. – Menelaos Kotsollaris May 15 '15 at 01:53
  • But I am targetting API 21 so I need to use getSupportFragmentManager – Lukas Anda May 15 '15 at 06:54
  • 1
    I updated my answer according to your issue, [see this](http://stackoverflow.com/questions/25306197/using-getfragmentmanager-vs-getsupportfragmentmanager) for more too. – Menelaos Kotsollaris May 15 '15 at 07:05