Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use MapView with FragmentManager and ListFragment

Tags:

android

My app is using a ListFragment on left side that the user can use to select what fragment to use on the right hand side.

In sort it seems impossible to show the MapView more than once. The first problem is that it only allow one instance of MapView per Activity.

# Exception 1:
You are only allowed to have a single MapView in a MapActivity

Therefore, I saved my MapView and container in the Activity class:

public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   FragmentManager.enableDebugLogging(true);
   setContentView(R.layout.main);
   mapViewContainer = LayoutInflater.from(this).inflate(R.layout.maplayout, null);
   mapView = (MapView) mapViewContainer.findViewById(R.id.map_view); 
}

However, this give me the next problem:

# Exception 2:
The specified child already has a parent. 
You must call removeView() on the child’s parent first.

I have tried to remove the view, using this code:

((ViewGroup)mapViewContainer).removeView(mapView);
((ViewGroup)mapView.getParent()).removeView(mapView);

Got a NullPointerExeption.

I would appreciate any good ideas, or if you could share if you have been successful in doing this?

Thanks :)

like image 745
Ben Avatar asked Oct 27 '11 15:10

Ben


1 Answers

Yeah, bumped into this one, too.

Do not add your MapView in XML layout file for your fragment. Instead, just leave a place for it, say, in a LinearLayout with id="@+id/your_map_container_id"

Declare a MapView private member in YourMapContainerFragment's:

public class YourMapContainerFragment extends Fragment {
    private MapView mMapView;
    //...

Then, go like this in YourMapContainerFragment's onCreateView():

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // ... Inflate your fragment's layout...
    // ...
    if (mMapView == null) {
        mMapView = new MapView(getActivity(), /*String*/YOUR_MAPS_API_KEY);
    } else {
        ((ViewGroup)mMapView.getParent()).removeView(mMapView);
    }
    ViewGroup mapContainer = (ViewGroup) fragmentLayout.findViewById(R.id.your_map_container_id);
    mapContainer.addView(mMapView);
    // ...
}

This will make the same MapView object be reused across removals/additions of your fragment to activity.

like image 125
Ivan Bartsov Avatar answered Sep 23 '22 16:09

Ivan Bartsov