Android谷歌地图片段

时间:2017-07-20 17:33:25

标签: java android google-maps android-fragments

我创建了一个新的Android项目,其中Google Map活动定义为

public class MapsActivity extends FragmentActivity implements   OnMapReadyCallback {

private GoogleMap mMap;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
}

布局就是这个

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.alewe.myapplication.MapsActivity" />

问题是: 我创建了另一个活动,我试图在其中添加谷歌地图片段。

使用

FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction().replace(R.id.firstLayout,this,this.getTag());

无效,因为我无法将FragmentActivity转换为Fragment。

如何添加刚刚在另一个活动中创建的Google地图片段? 感谢

1 个答案:

答案 0 :(得分:0)

像这样更改布局(activity_maps):

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  tools:context="com.example.alewe.myapplication.MapsActivity"
  android:id="@+id/main_view_map">

  <com.google.android.material.floatingactionbutton.FloatingActionButton
      android:id="@+id/button"
      app:layout_constraintTop_toTopOf="parent"
      app:layout_constraintRight_toRightOf="parent"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:elevation="10dp"
      app:fabSize="mini"
      app:srcCompat="@drawable/ic_refresh_black_24dp"
      android:layout_marginTop="16dp"
      android:layout_marginEnd="16dp" />

  <fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

不要使用

FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction().replace(R.id.firstLayout,this,this.getTag());

此代码。