how to add mapfragment inside a listview item within adapter?

一世执手 提交于 2019-12-05 13:31:25

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);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!