Danial
Danial

Reputation: 612

android google map supportmap fragment can't be initialized in fragment

I'm trying to create implement a Google-Map in android using fragment :

override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_map_test, container, false)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //the line below get's error
        val mapFragment = view?.findViewById<View>(R.id.sp_map_test) as SupportMapFragment
        mapFragment.getMapAsync(this)
    }

My XML :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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=".MapTestFragment">


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


</LinearLayout>

But it can't find the SupportMap Fragment. How can I resolve this ?

I have tried this also - val mapFragment = parentFragmentManager.findFragmentById(R.id.sp_map_test) as SupportMapFragment

null cannot be cast to non-null type com.google.android.gms.maps.SupportMapFragment

Upvotes: 0

Views: 150

Answers (2)

Uuu Uuu
Uuu Uuu

Reputation: 1282

You have to put it in onCreateView

override fun onCreateView(
            inflater: LayoutInflater, container: ViewGroup?,
            savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_map_test, container, false)
        val mapFragment = view?.findViewById<View>(R.id.sp_map_test) as SupportMapFragment
        mapFragment.getMapAsync(this)
    }

or you also create Support Map Fragment from template

In Android Studio select New -> Fragment -> Google Map Fragment

Upvotes: 0

Jyotish Biswas
Jyotish Biswas

Reputation: 574

Insted of

val mapFragment = view?.findViewById<View>(R.id.sp_map_test) as SupportMapFragment

and

val mapFragment = parentFragmentManager.findFragmentById(R.id.sp_map_test) as SupportMapFragment

Use

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

Reference MapFragment Referance

Upvotes: 1

Related Questions