我想以编程方式将此xml片段添加到其他片段。 有可能吗?
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
答案 0 :(得分:17)
在XML中,您可以添加占位符容器:
<FrameLayout
android:id="@+id/mapContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
然后在代码中你可以做到:
FragmentManager fm = getChildFragmentManager();
SupportMapFragment supportMapFragment = SupportMapFragment.newInstance();
fm.beginTransaction().replace(R.id.mapContainer, supportMapFragment).commit();
答案 1 :(得分:2)
制作如下布局:
<FrameLayout
android:id="@+id/layout_mapContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_weight="0"
android:background="@android:color/transparent"
android:orientation="vertical" >
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/transparent" />
</FrameLayout>
在活动声明中:
FrameLayout mapLayout = (FrameLayout)findViewById(R.id.layout_mapContainer);
像这样初始化地图:
private void initialiseMap() {
FragmentTransaction mTransaction = getSupportFragmentManager().beginTransaction();
SupportMapFragment mFRaFragment = new MapFragmentActivity();
mTransaction.add(mapLayout.getId(), mFRaFragment);
mTransaction.commit();
try {
MapsInitializer.initialize(context);
} catch (Exception e) {
e.printStackTrace();
}
}
这里MapFragmentActivity是类扩展SupportMapFragment