【问题标题】:Kotlin with Map in AndroidKotlin 与 Android 中的地图
【发布时间】:2018-01-04 11:12:37
【问题描述】:
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

【问题讨论】:

  • 确实初始化了fragmentManager
  • 直接使用它的getFragmentManager方法

标签: android dictionary kotlin


【解决方案1】:

您声明 mapFragment 可以为空,因此您必须处理它:

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

【讨论】:

  • 通过这种方式,您可以将mapFragment 声明为val。因为您只在它更安全时才分配它,因为它会阻止您将它重新分配给另一个值。 IDE 可能会告诉你
【解决方案2】:

该错误意味着您尝试将null 强制转换为SupportMapFragment。所以,先检查类型会更安全。

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

【讨论】:

    【解决方案3】:
    private lateinit var mMap: GoogleMap
    
     override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    
        val mapFragment: SupportMapFragment? = map as SupportMapFragment?
        mapFragment?.getMapAsync(this)
    }
    
    
    
    
    override fun onMapReady(googleMap: GoogleMap?) {
    
        if (googleMap != null) {
            mMap = googleMap
        }
    
        val sydney = LatLng(-34.0, 151.0)
        mMap.addMarker(MarkerOptions().position(sydney).title("Marker in Sydney"))
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney))
    }
    

    【讨论】:

    • 在kotlin android release版本中使用
    猜你喜欢
    • 2017-11-15
    • 2018-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-11
    • 2020-02-09
    • 2020-03-05
    • 1970-01-01
    相关资源
    最近更新 更多