我想将 thirdHourForecast 对象从 onSuccess 方法发送回调用它的 Activity 。 我想要解决这个问题的干净且最佳的解决方案。 这是我的代码。
天气预报处理程序类:
open class WeatherForecastHandler {
open fun getForecast(lat: Double, lng: Double, weatherKey: String){
val helper = OpenWeatherMapHelper(weatherKey)
helper.setUnits(Units.METRIC)
helper.setLang(Lang.ENGLISH)
helper.getThreeHourForecastByGeoCoordinates(lat, lng, object : ThreeHourForecastCallback {
override fun onSuccess(threeHourForecast: ThreeHourForecast) {//send this "threeHourForecast" object back to the place from which "getForecast()" method is called.}
override fun onFailure(throwable: Throwable) {
Log.d("forecast", throwable.message!!)
}
})
}
}
调用函数地点:
map Activity 类:
open class MapsActivity : FragmentActivity(), OnMapReadyCallback{
private lateinit var googleMap: GoogleMap
private lateinit var startPoint: LatLng
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_maps)
val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment?
mapFragment!!.getMapAsync(this)
val bundle: Bundle? = intent.getParcelableExtra("bundle")
startPoint = bundle!!.getParcelable("startPoint")!!
}
override fun onMapReady(map: GoogleMap?) {
googleMap = map!!
val weatherHandler = WeatherForecastHandler()
weatherHandler.getForecast(startPoint.latitude, startPoint.longitude, getString(R.string.key)
//I need object here.
}
最佳答案
尝试在函数类型参数中添加函数。就像,
天气预报处理程序类:
open fun getForecast(lat: Double, lng: Double, weatherKey: String, callback: ((result: ThreeHourForecast?) -> Unit)){
val helper = OpenWeatherMapHelper(weatherKey)
helper.setUnits(Units.METRIC)
helper.setLang(Lang.ENGLISH)
helper.getThreeHourForecastByGeoCoordinates(lat, lng, object : ThreeHourForecastCallback {
override fun onSuccess(threeHourForecast: ThreeHourForecast) {//send this "threeHourForecast" object back to the place from which "getForecast()" method is called.
callback(threeHourForecast)
}
override fun onFailure(throwable: Throwable) {
callback(null)
}
})
}
map Activity 类:
override fun onMapReady(map: GoogleMap?) {
googleMap = map!!
val weatherHandler = WeatherForecastHandler()
weatherHandler.getForecast(startPoint.latitude, startPoint.longitude, getString(R.string.key) { result: ThreeHourForecast? ->
// You can now receive value of 'threeHourForecast'
}
//I need object here.
}
关于java - 将对象从类传递到 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60587348/