im trying to fallow the google maps api guide on displaying a map in a fragment. But every time i call the support fragment manager it just keeps returning null to me. I don't know what im doing wrong and i thought my code was the same as the example.
. fragment:
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:id="@ id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
MainActivity
class MainActivity : AppCompatActivity(), OnMapReadyCallback {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val mapFragment = supportFragmentManager // right here keeps returning null
.findFragmentById(R.id.map) as SupportMapFragment
mapFragment.getMapAsync(this)
im sorry if this question is strange. im literally just figuring it out for the first time
CodePudding user response:
Try once
val mapFragment = supportFragmentManager
.findFragmentById(R.id.map) as SupportMapFragment?
mapFragment!!.getMapAsync(this)
CodePudding user response:
You can define the OnMapReadyCallback
on the top of the file as follows:
private val callback = OnMapReadyCallback { googleMap ->
//do your stuff
}
and in onViewCreated()
:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val mapFragment = childFragmentManager.findFragmentById(R.id.map) as SupportMapFragment?
mapFragment?.getMapAsync(callback)