6

How to use View binding in SupportMapFragment? ref my code

I have a map fragment in the layout, I want to use view bind in the fragment.

val mapFragment = childFragmentManager.findFragmentById(R.id.map) as SupportMapFragment

Plz Need solution..

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.SupportMapFragment
import com.zeddigital.zigmaster.R
import com.zeddigital.zigmaster.databinding.FragmentHomeBinding

class HomeFragment : Fragment() {
    private lateinit var mMap: GoogleMap

    private var binding : FragmentHomeBinding ?=null
    override fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?
    ): View {
        binding = FragmentHomeBinding.inflate(inflater)

        // binding.myTextView.text = "sample"

        val mapFragment = childFragmentManager.findFragmentById(R.id.map) as SupportMapFragment
        mapFragment.getMapAsync { googleMap ->

        }

        return binding!!.root
    }

    override fun onDestroyView() {
        super.onDestroyView()
        binding=null
    }
}





<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.home.HomeFragment">

    <fragment
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

2 Answers2

10

The above answer is correct but for the latest Android Studio, I am posting some code changes to it.

From now on it is recommended to use <androidx.fragment.app.FragmentContainerView /> instead of <fragment />.

Now you can use View binding as below:

For Java:

SupportMapFragment mapFragment = (SupportMapFragment) childFragmentManager.findFragmentById(binding.map.getId());

For Kotlin:

val mapFragment = childFragmentManager.findFragmentById(binding.map.id) as SupportMapFragment
kroegerama
  • 769
  • 9
  • 27
Smit Bhanvadia
  • 1,329
  • 2
  • 8
  • 5
8

If you want to use view binding for MapFragment's ID as mentioned in the quoted bounty message below:

How to use View binding in SupportMapFragment' ID?

What you can do is simply write

val mapFragment = childFragmentManager.findFragmentById(R.id.map) as SupportMapFragment

as

val mapFragment = childFragmentManager.findFragmentById(binding.map.id) as SupportMapFragment

This will prevent it from being null which is the case you want.

Lalit Fauzdar
  • 5,953
  • 2
  • 26
  • 50