Search code examples
androidandroid-viewbinding

How to Use View binding in SupportMapFragment?


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>

Solution

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