How to restore map object when fragment load second time

1.5k views Asked by At

I have to fragments one Fragment contains Map and other one to show details of pin when user clicks on map.When user clicks on back button from Details Fragment i am overriding the back button to show map again.

fragmentManager.beginTransaction().replace(R.id.content_frame, mapfragment).commit();

When i am doing like this the map is reloading.I tried with addToBackStack also but no luck.Can any one suggest how to resolve it..

3

There are 3 answers

1
Vikas B L On

Check this out. You need to save the state of the fragment.

0
vipul mittal On

Use following code:

getSupportFragmentManager().beginTransaction()
                           .add(detailFragment, "detail")
                           // Add this transaction to the back stack
                           .addToBackStack()
                           .commit();

Remove anything you have written in onBackPressed.

Try and let me know.

0
optimusfrenk On

When the SupportMapFragment is created, call the method setRetainInstance().

public class MapActivity extends AppCompatActivity implements OnMapReadyCallback {

private GoogleMap map;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.map);
    FragmentManager fm = getSupportFragmentManager();
    SupportMapFragment smf = (SupportMapFragment) fm.findFragmentById(R.id.map);
    smf.setRetainInstance(true);
    smf.getMapAsync(this);
}

@Override
public void onMapReady(GoogleMap googleMap) {
    this.map = googleMap;
    // put some markers
}

}

For more information go here.