无法在片段中对Google Maps API v2进行两次充气

时间:2013-12-05 21:29:24

标签: android google-maps android-fragments

好的,我已经检查了大约100个SO QA。

这是故事:我有一个SlidingMenu,可以说“创建事件”和“所有事件”项目。 “创建活动”菜单有一个地图片段,如下所示。用户选择“创建事件”并且地图在屏幕上没有错误,用户选择“所有事件”并显示事件,用户再次选择“创建事件”并繁荣:

Caused by: java.lang.IllegalArgumentException: Binary XML file line #45: Duplicate id 0x7f040058, tag null, or parent id 0x0 with another fragment for pl.mg6.android.maps.extensions.SupportMapFragment

每当用户从左侧菜单中选择时,都会创建CreateEventFragment:

public void showCreateNewEventFragment() {
    CreateEventFragment fragment = new CreateEventFragment();
    showFragment(fragment);
    slidingMenu.showContent();
}

create_event.xml

...    
<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_below="@+id/searchLayout"
    android:layout_marginTop="8dp"
    android:background="@color/app_color"
    android:padding="6dp" >

    <fragment
        android:id="@+id/map"
        android:name="pl.mg6.android.maps.extensions.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</RelativeLayout>
...

CreateEventFragment.java

public class CreateEventFragment extends BaseFragment {

    private GoogleMap mMap;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    setRetainInstance(true);
    View v = (View) inflater.inflate(R.layout.create_event, container,
            false);
    ((MainActivity) getActivity())
            .showSlidingMenu(LeftNavigation.ITEM_CREATE_NEW_EVENT);
    initGoogleMaps(v, savedInstanceState);
    return v;
}

private void initGoogleMaps(View v, Bundle savedInstanceState) {
    EventshipApplication app = (EventshipApplication) getActivity()
            .getApplication();
        SupportMapFragment mMapFragment = ((SupportMapFragment) getActivity()
                .getSupportFragmentManager().findFragmentById(R.id.map));
        mMap = mMapFragment.getExtendedMap();
        mMap.getUiSettings().setMyLocationButtonEnabled(true);
}
}

所以,我希望能够创建/使用MapFragment两次以上。有什么建议/解决方法吗?

编辑:

public void showFragment(Fragment fragment) {
    FragmentTransaction transaction = getSupportFragmentManager()
            .beginTransaction().add(android.R.id.content, fragment);
    transaction.addToBackStack(null);
    transaction.commit();
}

2 个答案:

答案 0 :(得分:1)

使用replace()代替add(),因为您第二次拨打android.R.id.content时已在showFragment()中有片段。

您可能还需要从后台堆叠弹出上一个交易,或者摆脱addToBackStack()来电。

答案 1 :(得分:0)

以下是解决方案:

v = app.getMapLayout();
    if (v == null) {
        v = (View) inflater.inflate(R.layout.create_event, container, false);
        app.setMapLayout(v);
    } else {
        ViewGroup parent = (ViewGroup) v.getParent();
        parent.removeView(v);
    }