I'm trying to use a MapFragment from the Google Maps Android API v2 in conjunction with a Camera preview. I need to be able to switch between the camera preview and the MapFragment, but I can’t make it work.
For the Camera preview, I’ve copied the CameraPreview class from the example guide. When I want to see the Camera preview, I add an instance of the CameraPreview class to my activity using
CameraPreview mPreview = new CameraPreview(this);
addContentView(mPreview, new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
This works fine when when I’m not using the MapFragment.
For the MapFragment, I’ve added it into my activity’s layout via
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<fragment
android:id="@+id/map"
android:layout_width="fill_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.MapFragment" />
</LinearLayout>
It works fine without the CameraPreview. I can hide and unhide the MapFragment using (e.g. for hide):
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.hide(map_fragment);
ft.commit();
However, the problem comes when I try and use the two together, i.e. hide the MapFragment and then add a CameraPreview instance into my activity. The hide doesn’t work, and it seems that the MapFragment somehow hijacks the CameraPreview and takes precedence. One strange feature is that if I force the screen to sleep and then wake it up, when it wakes up the CameraPreview is there. If I do it the other way round, i.e. add the CameraPreview first and then hide the MapFragment, the behavior is the same.
FYI: I'm testing the app on a Samsung Galaxy Note 2 LTE running Android Version 4.1.1.
Can anyone tell me what I’m doing wrong?
Use setZOrderOnTop(boolean) on your camerapreview like this mPreview.setZOrderOnTop(true);. It works for me.