-1
我嘗試將設備地理位置轉換爲片段並使用回調。但集後一次鏈接是空如何在Kotlin中設置CallBack?
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))
}
第一次callback is set and work (log)
但第一次調用鏈接後爲空。爲什麼?我如何解決這個問題?
好,如果它第一次工作,這意味着它沒有進入第二次onReceive方法,它不調用updateLocation方法。這意味着你沒有以正確的方式發送廣播。我猜你沒有把它放在onResume方法中,因爲onCreate只被調用一次,這就是爲什麼它只能在第一次。我只是猜測:) – Nenco
什麼是'行爲'?你確定'act'在'onActivityCreated'中不爲null嗎? – Naetmul
你在說什麼'link'? – chandil03