How to Hide Map Fragment - Android

Sun picture Sun · Feb 3, 2015 · Viewed 7.5k times · Source

Using below code to show and hide MapFragment, and it works just well:

public class MapFragmentActivity extends FragmentActivity {
...........
mMapFragment = ((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map));
googleMap = mMapFragment.getMap();  
googleMap.setMyLocationEnabled(true);
.....
if(isChecked)
  {                                 
        mMapFragment.getView().setVisibility(View.VISIBLE);                                     
  }
  else 
  {
        mMapFragment.getView().setVisibility(View.GONE);
  }

but whenever i am using it with Animation, Map never hides, it always visible, whereas animation works for me;

if(isChecked)
    {               
        mMapFragment.getView().setVisibility(View.VISIBLE);
        mMapFragment.getView().startAnimation(AnimationUtils.loadAnimation(MapFragmentActivity.this,
         R.anim.slide_up));
    }
    else 
    {
        mMapFragment.getView().setVisibility(View.GONE);
        mMapFragment.getView().startAnimation(AnimationUtils.loadAnimation(MapFragmentActivity.this,
         R.anim.slide_down));
    }

Answer

Skizo-ozᴉʞS picture Skizo-ozᴉʞS · Feb 3, 2015

You can try this

      private GoogleMap mMap;
    private SupportMapFragment mMapFragment;

if(isCheked) {
       mMapFragment = ((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.mapFragment));
    mMap = mMapFragment.getMap();
    
    mMapFragment.getView().setVisibility(View.Visible);
 
}
else {
   mMapFragment = ((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.mapFragment));
    mMap = mMapFragment.getMap();
    
    mMapFragment.getView().setVisibility(View.INVISIBLE);

}

Or the easy way is doing :

    if(isCheked) {
getSupportFragmentManager().beginTransaction().show(mFragment).commit();
               
        }
        else {
          getSupportFragmentManager().beginTransaction().hide(mFragment).commit();
        }

Try this out and let me know if it works.

Here's a snippet of the first method in Kotlin...

val mapFragment = supportFragmentManager
                .findFragmentById(R.id.map) as SupportMapFragment?
mapFragment?.view?.visibility = View.GONE