Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load new fragment in same space as current fragment

I'm looking for some advice on the best way to handle fragments which launch other fragments.

I'm converting an app which I started writing using a more Activity based approach and have since begun moving it over to using Fragments. I have some Fragments which used to launch a new Activity and I want to move them over to launching other Fragments in the same view that the current Fragment is residing.

For example - I have an Activity which has a WebView which uses a WebViewClient to handle internal js->java interactions. My WebViewClient can launch other Activities, which I used to do with :

 i = new Intent(context, GoogleMapActivity.class);
 startActivity(i);

This webview activity can either be fullscreen or in a view with a menu on the side, but I want the webview to respect the layout - so if the menu is present, it should stay present when launching new Fragments - I just don't know the best approach to writing the code which launches the Fragments.

So...is there a way, within a Fragment, of essentially telling a new Fragment to load in to the same space as the current Fragment or does there need to be some interaction with the Activity?

** EDIT **

Given that there are a few different layouts which could be used, I don't always know which id I should be targeting to put the fragment in - hence I need to know if there's a way to do this without knowing the id (as in the replace method for example).

like image 928
Martyn Avatar asked Oct 17 '11 12:10

Martyn


1 Answers

getFragmentManager().beginTransaction()
   .replace(((ViewGroup) getView().getParent()).getId(), fragment)
   .addToBackStack(null)
   .commit();

This should replace parent container with desired fragment.

like image 133
localhost Avatar answered Sep 30 '22 21:09

localhost