如何在Kotlin中设置回调?
我尝试将设备地理位置转换为片段并使用回调。 但设置一次后链接为空
fun updateLocation(location:LatLng){ Log.d(TAG,"Update fragment "+ localUpdater+" "+location) localUpdater?.tryOutLocation(location) } private inner class Receiver: BroadcastReceiver(){ override fun onReceive(context: Context?, intent: Intent?) { val bundle = intent?.extras!![AppConstants.LOCATION_BUNDLE] as Bundle val location = bundle.get(AppConstants.LOCATION_BUNDLE) as LatLng updateLocation(location) } } fun setUpdater(updater: IUpdateLocation){ this.localUpdater = updater Log.d(TAG,"Update fragment1 "+localUpdater) }
我声明回调:
private var localUpdater: IUpdateLocation? = null
代码界面:
interface IUpdateLocation { fun tryOutLocation(location:LatLng) }
片段代码:
override fun onActivityCreated(savedInstanceState: Bundle?) { act?.setUpdater(this) super.onActivityCreated(savedInstanceState) } override fun tryOutLocation(location: LatLng) { Log.d(TAG,"Update fragment map fragment "+location+" ") if(gMap != null){ gMap?.uiSettings?.isZoomGesturesEnabled gMap?.addMarker(MarkerOptions().position(location).title("Test")) gMap?.moveCamera(CameraUpdateFactory.newLatLngZoom(location, 20.0f)) }
第一次回调设置和工作(日志)
但是在第一次调用链接之后是空的。 为什么? 我如何解决这个问题?
我发现哪里错了。 我正在使用父类BaseActivity,其中是内部类Receiver。 在从BaseActivity继承的SplashActivity中,我创建了对象Receiver,并从BaseActivity继承的MainActivity中的片段创建了回调。 当我第一次设置回调,之后创建了Reciever时,情况就是如此。 我忍受了MainActivity中的所有过程并且工作。