4

I have a list view. I want to add a map inside each list item. The map will show/hide when I click on the list item. When the map shows, I can zoom, view location detail... on it. But I can't set MapFragment in the adapter. So, give me some solutions. Thank you.

gMap = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
googleMap = gMap.getMap();

I can't do that in getView.

Tri Ngo Minh
  • 145
  • 1
  • 9

1 Answers1

6

I just went through a similar problem and I came up with the following solution. By the way, now play services has google map lite mode.

You can see the entire example at: https://github.com/vinirll/MapListView

Let's suppose you have a ListView using an BaseAdapter, so you should override your getView method. This is how my getView looks like:

    @Override
public View getView(int position, View convertView, ViewGroup parent) {
    if ( convertView == null )
        convertView = new CustomItem(mContext,myLocations.get(position));

    return convertView;
}

Where class CustomItem is the FrameLayout that represents my row.

public class CustomItem extends FrameLayout {

public int myGeneratedFrameLayoutId;

public CustomItem(Context context,Location location) {
    super(context);
    myGeneratedFrameLayoutId = 10101010 + location.id; // choose any way you want to generate your view id

    LayoutInflater inflater = ((Activity) context).getLayoutInflater();

    FrameLayout view = (FrameLayout) inflater.inflate(R.layout.my_custom_item,null);
    FrameLayout frame = new FrameLayout(context);
    frame.setId(myGeneratedFrameLayoutId);

    int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 150, getResources().getDisplayMetrics());
    LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT,height);
    frame.setLayoutParams(layoutParams);

    view.addView(frame);

    GoogleMapOptions options = new GoogleMapOptions();
    options.liteMode(true);
    MapFragment mapFrag = MapFragment.newInstance(options);

    //Create the the class that implements OnMapReadyCallback and set up your map
    mapFrag.getMapAsync(new MyMapCallback(location.lat,location.lng));

    FragmentManager fm = ((Activity) context).getFragmentManager();
    fm.beginTransaction().add(frame.getId(),mapFrag).commit();

    addView(view);
}
Vinicius Lima
  • 1,601
  • 1
  • 12
  • 15
  • Why are you creating a new FrameLayout while the inflated view is also a FrameLayout? Seems a bit double... – Glenn85 Jul 23 '15 at 08:33
  • public static int myGeneratedFrameLayoutId = 10101010; this is so ugly – Marian Paździoch Sep 29 '15 at 06:22
  • I see that you added the fragment to the Listview, what about detaching the fragment when the view is recycled? Don`t we need to manage the lifecycle of the Fragment? – AmeyaB Oct 28 '15 at 22:58