Question

I have a google map inside a Tab. When I change tab, and come back to my google maps tab, the map is loading once more. Is there a way to load the map just once, and just get the instance when switching tab???

Here is my code :

Code for managing 2 tabs :

public class FragmentTabsPdv extends BaseActivity {
private ArrayList<Pdv> listaPdv;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    DatabaseHandlerTienda db = new DatabaseHandlerTienda(this);
    listaPdv = (ArrayList<Pdv>) db.getAllTiendas();

    ActionBar actionBar = getSupportActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    ActionBar.Tab tab1 = actionBar.newTab();
    tab1.setText("Lista");
    tab1.setIcon(R.drawable.ic_action_view_as_list);

    ActionBar.Tab tab2 = getSupportActionBar().newTab();
    tab2.setText("Mapa");
    tab2.setIcon(R.drawable.ic_action_location_map);
    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setTitle("");

    actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME
            | ActionBar.DISPLAY_SHOW_TITLE | ActionBar.DISPLAY_SHOW_CUSTOM);

    // create the two fragments we want to use for display content

    tab1.setTabListener(new TabListener<ListPdvTabFragment>(this,
            "lista", ListPdvTabFragment.class));
    tab2.setTabListener(new TabListener<MapPdvTabFragment>(this,
            "mapa", MapPdvTabFragment.class));

    actionBar.addTab(tab1);
    actionBar.addTab(tab2);
}

public ArrayList<Pdv> getListaPdv() {
    return listaPdv;
}

public void setListaPdv(ArrayList<Pdv> listaPdv) {
    this.listaPdv = listaPdv;
}

public static class TabListener<T extends Fragment> implements
        ActionBar.TabListener {
    private Fragment mFragment;
    private final Activity mActivity;
    private final String mTag;
    private final Class<T> mClass;

    /**
     * Constructor used each time a new tab is created.
     * 
     * @param activity
     *            The host Activity, used to instantiate the fragment
     * @param tag
     *            The identifier tag for the fragment
     * @param clz
     *            The fragment's Class, used to instantiate the fragment
     */
    public TabListener(Activity activity, String tag, Class<T> clz) {
        mActivity = activity;
        mTag = tag;
        mClass = clz;
    }

    /* The following are each of the ActionBar.TabListener callbacks */

    public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
        // Check if the fragment is already initialized
        if (mFragment == null) {
            // If not, instantiate and add it to the activity
            mFragment = Fragment.instantiate(mActivity, mClass.getName());
            ft.add(android.R.id.content, mFragment, mTag);
        } else {
            // If it exists, simply attach it in order to show it
            ft.attach(mFragment);
        }
    }

    public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
        if (mFragment != null) {
            // Detach the fragment, because another one is being attached
            ft.detach(mFragment);
        }
    }

    public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
        // User selected the already selected tab. Usually do nothing.
    }
}



}

Code for my Google Maps Tab :

public class MapPdvTabFragment extends SherlockFragment implements   GoogleMap.OnMarkerClickListener {
private MapView mapView;
private GoogleMap map;
private ArrayList<Pdv> pdvs;
private ViewPager pager;
private PagerAdapter pagerAdapter;
private View fragmentView;
boolean showNoResults = false;

// private HashMap<String, Pdv> markerToRestaurantAvailabilityMap = new
// HashMap();
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.tab_frag_map_pdv, container, false);
    fragmentView = v;
    Bundle localBundle = null;
    if (savedInstanceState != null)
        localBundle = (Bundle) savedInstanceState.getParcelable("mapViewBundle");

    // Gets the MapView from the XML layout and creates it
    mapView = (MapView) v.findViewById(R.id.map);

    // Gets to GoogleMap from the MapView and does initialization stuff

    mapView.onCreate(localBundle);
    mapView.onResume();// needed to get the map to display immediately
    map = mapView.getMap();
    map.getUiSettings().setMyLocationButtonEnabled(false);
    map.setOnMarkerClickListener(this);

    // Needs to call MapsInitializer before doing any CameraUpdateFactory
    // calls
    try {
        MapsInitializer.initialize(this.getActivity());
    } catch (GooglePlayServicesNotAvailableException e) {
        e.printStackTrace();
    }

    // Updates the location and zoom of the MapView
    map.setMyLocationEnabled(true);
    int zoom = 14;
    CameraUpdate here = CameraUpdateFactory.newLatLngZoom(new LatLng(19.359180, -99.180901), zoom);
    map.moveCamera(here);
    FragmentTabsPdv parent = (FragmentTabsPdv) getActivity();
    pdvs = parent.getListaPdv();
    if (pdvs != null && pdvs.size() > 0)
        showNoResults = false;
    else
        showNoResults = true;
    displayPdvOnMap(pdvs); // Display marker ( work well)
    initPager();
    return v;
}

@Override
public void onResume() {
    mapView.onResume();
    super.onResume();
}

@Override
public void onPause() {
    super.onPause();
    if (mapView != null)
        mapView.onPause();
}

@Override
public void onDestroy() {
    super.onDestroy();
    mapView.onDestroy();
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    if (mapView != null)
        mapView.onSaveInstanceState(outState);
}

@Override
public void onLowMemory() {
    super.onLowMemory();
    mapView.onLowMemory();
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

}

public void displayPdvOnMap(ArrayList<Pdv> tiendas) {
    for (Pdv pdv : tiendas) {
        Marker marker = map.addMarker(new MarkerOptions()
                .position(new LatLng(pdv.getLatitude(), pdv.getLongitude())).title(pdv.getTienda())
                .snippet(pdv.getCalle()));
        pdv.setMarker(marker);
    }
}

public void initPager() {

    pager = ((ViewPager) fragmentView.findViewById(R.id.pager));
    pager.setOffscreenPageLimit(3);
    pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        public void onPageScrollStateChanged(int paramAnonymousInt) {
        }

        public void onPageScrolled(int paramAnonymousInt1, float paramAnonymousFloat, int paramAnonymousInt2) {
        }

        public void onPageSelected(int position) {

            Pdv pdv = pdvs.get(position);
            Marker m = pdv.getMarker();
            m.showInfoWindow();
            // Center map on current marker
            CameraUpdate here = CameraUpdateFactory.newLatLngZoom(m.getPosition(), 14);
            map.animateCamera(here);

        }
    });
    pager.setSaveEnabled(false);
    pagerAdapter = new PagerAdapter() {

        public void destroyItem(ViewGroup paramAnonymousViewGroup, int paramAnonymousInt,
                Object paramAnonymousObject) {
            paramAnonymousViewGroup.removeView((View) paramAnonymousObject);
        }

        public int getCount() {

            if (showNoResults)
                return 1;
            if (pdvs != null)
                return pdvs.size();
            return 0;
        }

        public Object instantiateItem(View container, int position) {
            View view = null;
            if (showNoResults) {
                view = getLayoutInflater(null).inflate(R.layout.map_pager_empty, null);
            } else {
                view = getLayoutInflater(null).inflate(R.layout.row_lista_pdv, null);
                Pdv pdv = pdvs.get(position);
                TextView tienda_name = (TextView) view.findViewById(R.id.tienda_name);
                TextView direccion = (TextView) view.findViewById(R.id.tienda_dir);
                TextView contacto = (TextView) view.findViewById(R.id.tienda_contact);
                TextView horIni = (TextView) view.findViewById(R.id.tienda_horarioIni);
                TextView horFin = (TextView) view.findViewById(R.id.tienda_horarioFin);

                tienda_name.setText(pdv.getTienda());
                direccion.setText(pdv.getCalle());
                contacto.setText(pdv.getContacto());
                horIni.setText(pdv.getHorarioIni());
                horFin.setText(pdv.getHorarioFin());

            }

            ((ViewPager) container).addView(view, 0);
            return view;
        }

        public boolean isViewFromObject(View paramAnonymousView, Object paramAnonymousObject) {
            return paramAnonymousView == paramAnonymousObject;
        }
    };
    this.pager.setAdapter(this.pagerAdapter);
    return;
    // this.pager.removeAllViews();

}

@Override
public boolean onMarkerClick(Marker marker) {
    int i = 0;
    i = getPdvPosition(marker);
    if (i >= 0)
        pager.setCurrentItem(i, true);
    return false;
}

private int getPdvPosition(Marker marker) {
    int position = 0;
    for (Pdv pdv : pdvs) {
        Marker m = pdv.getMarker();
        String mId1 = m.getId();
        String mId2 = marker.getId();
        if (mId1.equals(mId2)) {
            return position;
        }
        position++;
    }
    return 0;
}


}
Was it helpful?

Solution

The lightest-weight way to show one fragment and hide another is via show() and hide().

attach() and detach() have a similar effect in terms of what the user sees, but also trigger onAttach() and onDetach() lifecycle methods in the fragment. Some fragments do nothing here. Other fragments may do more work here. Presumably, the Maps V2 fragments do more work here.

This may cause problems in other scenarios as well, such as using FragmentStatePagerAdapter, which (IIRC) uses attach() and detach() under the covers.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top