Kotlin在Android中使用Map

override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View { var view: View = inflater?.inflate(R.layout.map_fragment, null)!! var mapFragment : SupportMapFragment?=null mapFragment= fragmentManager.findFragmentById(R.id.map) as SupportMapFragment mapFragment.getMapAsync(this) return view } 

Logcat:

 FATAL EXCEPTION: main kotlin.TypeCastException: null cannot be cast to non-null type com.google.android.gms.maps.SupportMapFragment at example.com.kotlinexamplebydimple.Mapfragment.onCreateView(Mapfragment.kt:36) 

在这行上错误显示:

 mapFragment= fragmentManager.findFragmentById(R.id.map) as SupportMapFragment 

    你声明mapFragment是空的,所以你必须处理它:

     var mapFragment : SupportMapFragment?=null mapFragment = fragmentManager.findFragmentById(R.id.map) as SupportMapFragment? mapFragment?.getMapAsync(this) 

    该错误意味着您尝试将一个null投射到SupportMapFragment 。 因此,首先检查类型会更安全。

     val mapFragment = fragmentManager.findFragmentById(R.id.map) if (mapFragment is SupportMapFragment) { mapFragment.getMapAsync(this) }