如何以编程方式添加地图片段

2022-09-04 01:31:01

我想以编程方式将此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" />

答案 1

在 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();

答案 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 is class extend supportMapFragment


推荐