在Tab中优化Google地图的实例(Sherlock ActionBar)

时间:2014-03-24 15:46:51

标签: android google-maps tabs actionbarsherlock

我在Tab中有一个谷歌地图。当我更改标签并返回到我的谷歌地图标签时,地图再次加载。有没有办法只加载一次地图,只需在切换标签时获取实例???

这是我的代码:

管理2个标签的代码:

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.
    }
}



}

我的Google地图标签代码:

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;
}


}

1 个答案:

答案 0 :(得分:0)

显示一个片段并隐藏另一个片段的最轻量级方式是show()hide()

attach()detach()在用户看到的内容方面具有类似的效果,但也会在片段中触发onAttach()onDetach()生命周期方法。有些片段在这里什么都不做其他片段可能在这里做更多工作。据推测,Maps V2片段在这里做了更多工作。

这可能会导致其他情况出现问题,例如使用FragmentStatePagerAdapter,其中(IIRC)使用attach()detach()