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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29697884/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 15:44:55  来源:igfitidea点击:

How to add map fragment programmatically

javaandroidgoogle-maps

提问by user3910670

I would like add this xml fragment programmatically to other fragments. Is it possible?

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

回答by Numan1617

In XML you can add a placeholder container:

在 XML 中,您可以添加占位符容器:

<FrameLayout
        android:id="@+id/mapContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

And then in code you can do:

然后在代码中你可以这样做:

FragmentManager fm = getChildFragmentManager();
SupportMapFragment supportMapFragment =  SupportMapFragment.newInstance();
fm.beginTransaction().replace(R.id.mapContainer, supportMapFragment).commit();

回答by Pankaj

Make a layout like:

进行如下布局:

 <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>

In Activity declare :

在活动中声明:

FrameLayout mapLayout = (FrameLayout)findViewById(R.id.layout_mapContainer);

initialise map like this:

像这样初始化地图:

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

    }

Here MapFragmentActivity is class extends SupportMapFragment

这里 MapFragmentActivity 是类扩展 SupportMapFragment