Solution as following:
- Implement
OnMapReadyCallback
inViewHolder
class. - In
onMapReady
, callMapsInitializer.initialize
, to gaurantee features can to be used before obtaining a map.
Use this class to initialize the Google Maps Android API if features need to be used before obtaining a map. It must be called because some classes such as BitmapDescriptorFactory and CameraUpdateFactory need to be initialized.
- Recycle map from
onViewRecycled
.
public class NearbyStopsAdapter extends RecyclerView.Adapter<NearbyStopsAdapter.ViewHolder> {
@Override
public void onBindViewHolder(ViewHolder holder, int position)
{
//get 'location' by 'position' from data list
//get GoogleMap
GoogleMap thisMap = holder.gMap;
//then move map to 'location'
if(thisMap != null)
//move map to the 'location'
thisMap.moveCamera(...);
}
//Recycling GoogleMap for list item
@Override
public void onViewRecycled(ViewHolder holder)
{
// Cleanup MapView here?
if (holder.gMap != null)
{
holder.gMap.clear();
holder.gMap.setMapType(GoogleMap.MAP_TYPE_NONE);
}
}
public class ViewHolder extends RecyclerView.ViewHolder implements OnMapReadyCallback {
GoogleMap gMap;
MapView map;
... ...
public ViewHolder(View view) {
super(view);
map = (MapView) view.findViewById(R.id.mapImageView);
if (map != null)
{
map.onCreate(null);
map.onResume();
map.getMapAsync(this);
}
}
@Override
public void onMapReady(GoogleMap googleMap) {
//initialize the Google Maps Android API if features need to be used before obtaining a map
MapsInitializer.initialize(getApplicationContext());
gMap = googleMap;
//you can move map here to item specific 'location'
int pos = getPosition();
//get 'location' by 'pos' from data list
//then move to 'location'
gMap.moveCamera(...);
... ...
}
}
}