如何判断Kotlin是否已初始化变量?

时间:2018-11-17 23:39:00

标签: android kotlin

我在此应用程序中出于某种原因声明一个始终为null的变量。变量位于onClusterItemClick内部,称为标记(我在变量所在的位置加了注释)。我是kotlin的新手,我真的需要一些帮助来找出为什么变量为null的原因。这是我的代码

class MapFragment: BaseFragment<FragmentMapBinding, MapViewModel>(),OnMapReadyCallback,
        ClusterManager.OnClusterClickListener<Station>,ClusterManager.OnClusterItemClickListener<Station>{


    /**
     * Making Map fragment public
     */
    companion object {
        fun newInstance() = MapFragment()
    }


    /**
     * Variables
     */
    @Inject
    lateinit var viewModelFactory: ViewModelProvider.Factory
    private var stationList = mutableListOf<Station>()
    lateinit var mClusterManager: ClusterManager<Station>
    lateinit var mGoogleMaps:GoogleMap
    lateinit var renderer: DefaultClusterRenderer<Station>

    /**
     * Base Fragment methods
     */
    override fun layoutToInflate() = R.layout.fragment_map

    override fun defineViewModel() = ViewModelProviders.of(this, viewModelFactory).get(MapViewModel::class.java)

    override fun doOnCreated() {
        mapView.onCreate(null)
        mapView.onResume()
        mapView.getMapAsync(this)
        viewModel.getStations(activity?.supportFragmentManager!!, R.id.fragment_container, context!!)
        viewModel.retrieveStations().observe(this, Observer<List<Station>> {
            addItems(it)
            mClusterManager?.addItems(stationList)
        })
    }


    /**
     * Google maps methods
     */
    override fun onMapReady(googleMap: GoogleMap) {
        MapsInitializer.initialize(context )
        mGoogleMaps = googleMap
        googleMap.mapType = GoogleMap.MAP_TYPE_NORMAL
        //mGoogleMaps.moveCamera(CameraUpdateFactory.newLatLngZoom(LatLng(51.503186, -0.126446), 10f))
        mClusterManager = ClusterManager(context, mGoogleMaps)
        renderer = StationRenderer(context!!,mGoogleMaps, mClusterManager!!)
        mClusterManager?.setRenderer(StationRenderer(context!!,mGoogleMaps, mClusterManager!!))
        mGoogleMaps.setOnCameraIdleListener(mClusterManager)
        mGoogleMaps.setOnMarkerClickListener(mClusterManager)
        mClusterManager?.setOnClusterClickListener(this)
        mClusterManager?.setOnClusterItemClickListener(this)
    }


    /**
     * Cluster Listeners
     */
    override fun onClusterClick(cluster: Cluster<Station>?): Boolean {
        val builder = LatLngBounds.builder()
        for (item in cluster?.items!!) {
            builder.include(item.position)
        }
        val bounds = builder.build()
        try {
            mGoogleMaps.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 100))
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return true
    }


    override fun onClusterItemClick(p0: Station?): Boolean {
        dragView.visibility = View.VISIBLE
        val marker = renderer.getMarker(p0) //marker is always null
        Log.e("CheckIfMarkerIsNull",marker.id) //marker is always null here
        return true
    }


    /**
     * Aux method to populate pin points
     */
    fun addItems(items: List<Station>){
        stationList.addAll(items)
    }


    /**
     * Class to design the pin point into the map
     */

    inner class StationRenderer(context: Context, map: GoogleMap,
                                clusterManager: ClusterManager<Station>) : DefaultClusterRenderer<Station>(context, map, clusterManager) {


        override fun onBeforeClusterRendered(cluster: Cluster<Station>?, markerOptions: MarkerOptions?) {
            markerOptions?.icon(BitmapDescriptorFactory.fromBitmap(createStoreMarker(cluster?.size.toString())))
        }

        override fun onBeforeClusterItemRendered(item: Station?, markerOptions: MarkerOptions?) {
            markerOptions?.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_map_pin))
        }


        private fun createStoreMarker(stationsCount:String): Bitmap {
            val markerLayout = layoutInflater.inflate(R.layout.marker_item, null)
            val markerImage = markerLayout.findViewById(R.id.marker_image) as ImageView
            val markerRating = markerLayout.findViewById(R.id.marker_text) as TextView
            markerImage.setImageResource(R.drawable.ic_map_pin)
            markerRating.text = stationsCount
            markerLayout.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED))
            markerLayout.layout(0, 0, markerLayout.getMeasuredWidth(), markerLayout.getMeasuredHeight())
            val bitmap = Bitmap.createBitmap(markerLayout.getMeasuredWidth(), markerLayout.getMeasuredHeight(), Bitmap.Config.ARGB_8888)
            val canvas = Canvas(bitmap)
            markerLayout.draw(canvas)
            return bitmap
        }


        override fun shouldRenderAsCluster(cluster: Cluster<Station>?): Boolean {
            return cluster?.size !!> 1
        }


    }

}

2 个答案:

答案 0 :(得分:1)

Kotlin 1.2中,您可以检查lateinit变量的初始化状态:

if (::variable.isInitialized) { ... }

在您的情况下:

if (:: renderer.isInitialized) {
    // Do something
}

答案 1 :(得分:0)

由于您未声明变量类型,因此将假定它可以为空

val marker: Type? = renderer.getMarker(p0)

因此,从技术上讲,它只是用值null

进行初始化

看起来您的渲染器可能没有得到应有的使用?在这里稍微修改了代码;

   /**
     * Google maps methods
     */
    override fun onMapReady(googleMap: GoogleMap) {
        MapsInitializer.initialize(context )
        mGoogleMaps = googleMap
        googleMap.mapType = GoogleMap.MAP_TYPE_NORMAL
        //mGoogleMaps.moveCamera(CameraUpdateFactory.newLatLngZoom(LatLng(51.503186, -0.126446), 10f))
        mClusterManager = ClusterManager(context, mGoogleMaps)
        renderer = StationRenderer(context!!,mGoogleMaps, mClusterManager!!)
        mClusterManager?.setRenderer(renderer)
        mGoogleMaps.setOnCameraIdleListener(mClusterManager)
        mGoogleMaps.setOnMarkerClickListener(mClusterManager)
        mClusterManager?.setOnClusterClickListener(this)
        mClusterManager?.setOnClusterItemClickListener(this)
    }

    override fun onClusterItemClick(p0: Station?): Boolean {
        dragView.visibility = View.VISIBLE
        val marker = renderer.getMarker(p0) //marker is always null
        Log.e("CheckIfMarkerIsNull",marker.id) //marker is always null here
        return true
    }