Android Fragmentの中にSupportMapFragmentを配置する。

個人開発したアプリの宣伝
目的地が設定できる手帳のような使い心地のTODOアプリを公開しています。
Todo with Location

Todo with Location

  • Yoshiko Ichikawa
  • Productivity
  • Free

スポンサードリンク

例えばViewPagerに配置したFragmentに地図を配置したい場合などなど。

そのままFragmentのレイアウトにベタっとSupportMapFragmentを配置して、

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".ParentFragment">

    <fragment
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        ...
/>
</androidx.constraintlayout.widget.ConstraintLayout>

親Fragment側から、findFragmentByIdすれば取得できるかなーなんて思ってたけど、ダメだった。

fragmentManager?.findFragmentById(R.id.map)  //return null

実装例

FragmentTransactionからreplaceするやり方で配置できる

layout
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".ParentFragment">

        <FrameLayout
            android:id="@+id/map"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
ParentFragment
lateinit var mMap:GoogleMap

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    val fragmentTransaction = fragmentManager?.beginTransaction()
    fragmentTransaction?.let{
        val mapFragment = SupportMapFragment()
        mapFragment.getMapAsync(this)
        fragmentTransaction.replace(R.id.map, mapFragment);
        fragmentTransaction.commit();
    }
    super.onViewCreated(view, savedInstanceState)
}

override fun onMapReady(googleMap: GoogleMap) {
    mMap = googleMap
}